typestar

Iterator adapters in Rust

Chaining map, filter, and collect over an iterator.

fn main() {
    let nums = vec![1, 2, 3, 4, 5, 6];

    let evens: Vec<i32> = nums
        .iter()
        .filter(|&&n| n % 2 == 0)
        .map(|&n| n * 10)
        .collect();

    let total: i32 = nums.iter().sum();
    println!("{evens:?} {total}");
}

How it works

  1. filter keeps matching items; map transforms them.
  2. collect gathers the results into a Vec.
  3. sum reduces the iterator to one value.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
208
Tokens
90
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 1 of 5 in Adapters, step 1 of 14 in Iterators & closures.

Next →