Prepend A Lazy Header With once_with

Prepend one lazily computed element to a stream with once_with: the closure runs only when the iterator is consumed, never at construction time.

RustCli Tooling

Code

rustsnippet
17 lines
use std::iter::once_with;

fn report(rows: &[&str]) -> impl Iterator<Item = String> + '_ {
    // 头部行只在流被真正消费时才计算
    once_with(|| format!("report with {} rows", rows.len()))
        .chain(rows.iter().map(|r| format!("row: {r}")))
}

fn main() {
    for line in report(&["deploy", "verify"]) {
        println!("{line}");
    }

    // 构造但不消费:闭包完全不执行
    let _unused = report(&["a", "b"]);
    println!("constructed without consuming");
}

Lazy by construction

report(rows) returns impl Iterator<Item = String> + '_: the header comes from once_with(|| format!("report with {} rows", rows.len())) and is chained onto rows.iter().map(|r| format!("row: {r}")). The closure inside once_with runs only when the iterator is first consumed — report(&["a", "b"]) assigned to _unused in main constructs the stream without ever calling it, and the file prints constructed without consuming as proof.

What the consumed stream yields

report with 2 rows
row: deploy
row: verify
constructed without consuming

The for line in report(&["deploy", "verify"]) loop draws the lazily computed header first — rows.len() is 2 at consumption time — then the two chained row lines. The final line shows main continuing after the unconsumed stream, which cost nothing but an iterator value.

The line that defers the work

once_with(|| format!("report with {} rows", rows.len()))
    .chain(rows.iter().map(|r| format!("row: {r}")))

Swapping once_with for an eager format! would compute the header on every report call, consumed or not — the closure is what makes the header part of the stream rather than part of construction.

Interactive Tools for This Topic

FAQ

What does Prepend A Lazy Header With once_with print when run?
Execute the whole file; each printed line is prefixed with a label like `constructed without consuming`.