RRust By Example
intermediateIterators

FlatMap and Flatten

Flatten nested iterators with flat_map and flatten.

FlatMap and Flatten

Flatten nested iterators with flat_map and flatten.

Difficulty

Intermediate

Code

rust
fn main() {
    // flat_map: one-to-many mapping
    let words = vec!["hello world", "foo bar"];
    let chars: Vec<&str> = words.iter()
        .flat_map(|s| s.split_whitespace())
        .collect();
    println!("words: {:?}", chars);

    // flatten nested Option
    let data = vec![Some(1), None, Some(3), None, Some(5)];
    let values: Vec<i32> = data.into_iter().flatten().collect();
    println!("values: {:?}", values);

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

    // parse multiple strings
    let strings = vec!["1", "two", "3", "four"];
    let numbers: Vec<i32> = strings.iter()
        .flat_map(|s| s.parse::<i32>())
        .collect();
    println!("parsed: {:?}", numbers);
}

Explanation

flat_map maps and flattens. flatten removes nesting.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the iterators category to build a complete understanding of this topic.

More Iterators Examples