typestar

filter_map and flat_map in Rust

Mapping and filtering in one pass, and flattening nested structure.

fn main() {
    let raw = ["3", "x", "7", "", "12"];

    let nums: Vec<i32> = raw
        .iter()
        .filter_map(|s| s.parse().ok())
        .collect();
    println!("{:?}", nums);

    let words = ["hot key", "cold start"];
    let parts: Vec<&str> = words
        .iter()
        .flat_map(|line| line.split(' '))
        .collect();
    println!("{:?}", parts);

    let nested = vec![vec![1, 2], vec![3], vec![]];
    println!("{:?}", nested.into_iter().flatten().collect::<Vec<i32>>());
}

How it works

  1. filter_map keeps every Some the closure returns.
  2. flat_map maps to iterators and concatenates them.
  3. flatten does the same for an iterator of collections.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
419
Tokens
178
Three-star pace
95 tpm

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

Type this snippet

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

← Previous Next →