Repeat Builds Padding And Patterns

Generate fixed-width separators, indentation, and repeated patterns with str::repeat, which allocates once instead of concatenating in a loop.

RustCli Tooling

Code

rustsnippet
22 lines
fn banner(title: &str, width: usize) -> String {
    // repeat 一次分配生成定宽分隔线
    let line = "=".repeat(width);
    let pad = (width.saturating_sub(title.len() + 4)) / 2;
    format!("{line}\n{} {title} {}\n{line}", " ".repeat(pad), " ".repeat(pad))
}

fn main() {
    println!("{}", banner("deploy report", 40));

    // 简单缩进:两级嵌套输出用 repeat 控制层级
    let indent = "  ".repeat(2);
    println!("{indent}- nested item");

    // repeat(0) 合法:得到空串,无需特判
    println!("empty: {:?}", "".repeat(0));

    // 重复字符构成进度条片段
    let done = 7;
    let total = 10;
    println!("[{}{}]", "#".repeat(done), ".".repeat(total - done));
}

How it works

The working surface is the functions banner and main — everything else is wiring.

Applying it

Signature: fn banner(title: &str, width: usize) -> String

Running the file prints labeled results such as empty: — each operation’s effect is visible in the output.

There are 1 call inside main — banner — executed top to bottom.

Statements that matter

fn banner(title: &str, width: usize) -> String {
// repeat 一次分配生成定宽分隔线
let line = "=".repeat(width);
let pad = (width.saturating_sub(title.len() + 4)) / 2;
format!("{line}\n{} {title} {}\n{line}", " ".repeat(pad), " ".repeat(pad))
}

Interactive Tools for This Topic

FAQ

What does Repeat Builds Padding And Patterns print when run?
Run it as a complete program — the output lines carry labels such as `empty:`.