Seed Pipelines With once And empty

Adapt one-item and no-item cases to any iterator pipeline: iter::once lifts a single value, iter::empty supplies a legal zero-element placeholder.

RustCli Tooling

Code

rustsnippet
26 lines
use std::iter;

// the pipeline consumer only asks for impl Iterator: call sites adapt one item and zero items with once/empty
fn render(lines: impl Iterator<Item = String>) -> String {
    lines.map(|l| format!("| {l}")).collect::<Vec<_>>().join("\n")
}

fn main() {
    // once: a single message rides the same pipeline
    println!("{}", render(iter::once("build ok".to_string())));

    // empty: zero messages are also a valid iterator, so the call site needs no if branch
    println!("{}", render(iter::empty()));

    // once chains a fixed header row with dynamic rows into a mini report
    let rows = ["deploy", "verify"].map(|r| format!("step {r}"));
    let report = iter::once("== report ==".to_string())
        .chain(rows)
        .collect::<Vec<_>>()
        .join("\n");
    println!("{report}");

    // empty collected into any target collection stays empty: a fallback for generic interfaces
    let nothing: Vec<String> = iter::empty().collect();
    println!("nothing: {nothing:?}");
}

How it works

Seed Pipelines With once And empty is built around the functions render and main.

Putting it to use

The main signature reads fn render(lines: impl Iterator<Item = String>) -> String

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

Execute the file and main walks through render, in that order.

Core lines

fn render(lines: impl Iterator<Item = String>) -> String {
lines.map(|l| format!("| {l}")).collect::<Vec<_>>().join("\n")
}
let rows = ["deploy", "verify"].map(|r| format!("step {r}"));
let nothing: Vec<String> = iter::empty().collect();

Interactive Tools for This Topic

FAQ

What does Seed Pipelines With once And empty print when run?
Run it as a complete program — the output lines carry labels such as `nothing:`.