Pad Rows To Fixed Width With repeat_n
Right-pad short rows to a fixed width by chaining repeat_n onto the row iterator; the count saturates to zero when the row is already full.
Code
use std::iter::repeat_n;
fn pad_row(cells: &[&str], width: usize) -> Vec<String> {
cells
.iter()
.map(|cell| cell.to_string())
.chain(repeat_n("-".to_string(), width.saturating_sub(cells.len())))
.collect()
}
fn main() {
// 短行补齐到 5 列
let header = pad_row(&["task", "owner", "state"], 5);
println!("{header:?}");
// 刚好满宽:repeat_n 产出 0 个元素
let full = pad_row(&["a", "b"], 2);
println!("{full:?}");
// 单独使用:固定长度的占位序列
let placeholders: Vec<&str> = repeat_n("-", 3).collect();
println!("{placeholders:?}");
}Padding by chaining
pad_row maps each cell to an owned String, then chains repeat_n(“-”.to_string(), width.saturating_sub(cells.len())) and collects — short rows gain exactly the fillers they lack. The header row prints with two dashes appended.
Saturating subtraction
width.saturating_sub(cells.len()) yields 0 for a full row, so repeat_n produces nothing and the full row prints unchanged — no underflow, no negative count.
Standalone use
Collecting repeat_n(“-”, 3) alone builds a fixed-length placeholder vector, printed as the placeholders line — the same iterator serving both fill and generation roles.
Interactive Tools for This Topic
FAQ
- Why saturating_sub instead of plain subtraction?
- On usize a plain width - cells.len() would underflow-panic for full rows; the saturating form yields 0, and repeat_n of 0 produces nothing.
- What does repeat_n produce for count 0?
- An empty iterator — the full row passes through unchanged, which the demo prints as-is.
Report a problem with this exampleOpens a pre-filled issue on GitHub.