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.

RustCli Tooling

Code

rustsnippet
21 lines
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

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.