Rust

Iterator Chain — map / filter / collect

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Rust iterators are lazy and zero-cost. Chain transformations and finally collect into a concrete container. The compiler unrolls the whole pipeline into a tight loop.
Rust
Raw
fn main() {
    let nums = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    let squares_of_evens: Vec<i32> = nums.iter()
        .filter(|&&n| n % 2 == 0)
        .map(|&n| n * n)
        .collect();
    println!("{:?}", squares_of_evens);              // [4, 16, 36, 64, 100]

    // collect can produce different containers
    let as_strings: Vec<String> = nums.iter().map(|n| n.to_string()).collect();
    println!("{:?}", as_strings);

    // sum / product / count are eager terminators
    let sum: i32     = nums.iter().sum();
    let product: i64 = nums.iter().map(|&n| n as i64).product();
    println!("sum={sum} product={product}");

    // chunked aggregates: sum of squares
    let s: i64 = (1..=100).map(|n: i64| n * n).sum();
    println!("Σ(1..=100)² = {s}");                   // 338350
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.