Iterator Adapters Do Nothing Until Collect
Chain filter and map without doing work: adapters build a pipeline that collect, sum, or a for loop drives, so no intermediate collections appear.
Code
fn main() {
let nums = vec![5, 2, 8, 1, 9, 3];
// Adapters only assemble the pipeline; no traversal has happened
let pipeline = nums.iter().filter(|n| **n > 2).map(|n| n * 10);
println!("pipeline built, nothing ran yet");
// collect is what drives the whole pipeline
let out: Vec<i32> = pipeline.collect();
println!("{out:?}");
// The same pipeline with a different driver: sum consumes the iterator straight into a total
let total: i32 = nums.iter().filter(|n| **n > 2).map(|n| n * 10).sum();
println!("total: {total}");
// A for loop consuming items one by one drives the pipeline too
for v in nums.iter().filter(|n| **n % 2 == 0) {
println!("even: {v}");
}
}Inside the snippet
The code’s whole job belongs to the function main.
The one repetition in this snippet is the loop for v in nums.iter().filter(|n| **n % 2 == 0).
Watch out for
- The imports (if any) point only at standard-library modules.
Using it
The main signature reads fn main()
Each run prints the 3 labeled blocks pipeline built, nothing ran yet, total:, even: in source order.
Key statements
let total: i32 = nums.iter().filter(|n| **n > 2).map(|n| n * 10).sum();
let pipeline = nums.iter().filter(|n| **n > 2).map(|n| n * 10);
for v in nums.iter().filter(|n| **n % 2 == 0) {
println!("even: {v}");
}
FAQ
- What does Iterator Adapters Do Nothing Until Collect print when run?
- No setup needed: run the file and look for labeled lines like `pipeline built, nothing ran yet`, `total:`, `even:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.