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.
Code
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
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 Seed Pipelines With once And empty print when run?
- Run it as a complete program — the output lines carry labels such as `nothing:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.