expression
Iterator pipelines and optimization
Compare equivalent loop and iterator implementations before measuring. A lazy pipeline can avoid an intermediate vector; the compiler may inline and combine operations. Neither syntax guarantees faster execution. Do not confuse optimization fusion with FusedIterator exhaustion semantics. Expected stdout (not executed): 56 56 Common mistake: Using debug-build timing or assuming that collect is always allocation-free.
Formal Syntax & Structure
rust syntaxrust
iter().filter(...).map(...).sum::<T>()Working Example
Example Snippetrust
fn main() { let data = [1_u32, 2, 3, 4, 5, 6]; let mut loop_total = 0; for n in data { if n % 2 == 0 { loop_total += n * n; } } let iter_total: u32 = data.iter().copied().filter(|n| n % 2 == 0).map(|n| n * n).sum(); assert_eq!(loop_total, iter_total); println!("{loop_total} {iter_total}");}