Build Strings Incrementally With fmt::Write
The fmt::Write trait lets write! and writeln! append formatted text into a String without allocating an intermediate value per iteration.
Code
use std::fmt::Write;
fn main() {
// fmt::Write 直接往 String 里追加:write! 返回 Result,
// String 的实现不会失败,用 let _ 收掉
let mut report = String::new();
let _ = write!(report, "jobs: {}\n", 3);
// 循环累积:writeln! 带换行,每轮不分配新的中间 String
let names = ["scan", "lint", "test"];
for (i, name) in names.iter().enumerate() {
let _ = writeln!(report, " {}. {}", i + 1, name);
}
let _ = write!(report, "total: {}", names.len());
print!("{report}");
// 对比 format!:每次调用都新建 String,累积场景成本更高
let one = format!("{}\n", "line");
print!("format! makes: {one:?}");
}Inside the snippet
Count the function main as the entire surface area of Build Strings Incrementally With fmt::Write.
Iteration happens inside for (i, name) in names.iter().enumerate() — everything outside it runs once.
Core lines
for (i, name) in names.iter().enumerate() {
let _ = writeln!(report, " {}. {}", i + 1, name);
}
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.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.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- How do you run Build Strings Incrementally With fmt::Write?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.