Flat Map Transforms Then Flattens

Replace nested map-then-flatten chains with flat_map, turning one input into several outputs inside a single lazy iterator pass.

RustData Integrity

Code

rustsnippet
24 lines
fn words(line: &str) -> impl Iterator<Item = &str> {
    line.split_whitespace()
}

fn main() {
    let lines = ["rust ships iterators", "with flat_map built in"];

    // flat_map:每个元素映射成一个迭代器后拼接展平
    let tokens: Vec<&str> = lines.iter().flat_map(|l| words(l)).collect();
    println!("tokens: {tokens:?}");

    // 与 map + flatten 完全等价,只是少一层嵌套
    let same: Vec<&str> = lines.iter().map(|l| words(l)).flatten().collect();
    println!("same:  {same:?}");

    // 典型场景:把每行按分隔符拆成字段再统一处理
    let csv = ["1,2", "3,4"];
    let nums: Vec<u32> = csv
        .iter()
        .flat_map(|row| row.split(','))
        .filter_map(|f| f.parse().ok())
        .collect();
    println!("nums: {nums:?}");
}

What the code does

What another module actually calls is the functions words and main — everything else is wiring.

Applying it

The signature doing the primary work is fn words(line: &str) -> impl Iterator<Item = &str>

The demo output is labeled (tokens:, same:, nums:), so the output doubles as a step-by-step trace of what the file did.

There are 1 call inside main — words — executed top to bottom.

Statements that matter

let same: Vec<&str> = lines.iter().map(|l| words(l)).flatten().collect();
let tokens: Vec<&str> = lines.iter().flat_map(|l| words(l)).collect();
fn words(line: &str) -> impl Iterator<Item = &str> {
line.split_whitespace()
}

Interactive Tools for This Topic

FAQ

What does Flat Map Transforms Then Flattens print when run?
No setup needed: run the file and look for labeled lines like `tokens:`, `same:`, `nums:` in the output.