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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.