62. Iterator::flat_map — Map and Flatten in One Step
Need to transform each element into multiple items and collect them all into a flat sequence? flat_map combines map and flatten into a single, expressive call.
The nested iterator problem
Say you have a list of sentences and want all individual words. The naive approach with map gives you an iterator of iterators:
| |
You could chain .map().flatten(), but flat_map does both at once:
| |
Expanding one-to-many relationships
flat_map shines when each input element maps to zero or more outputs. Think of it as a one-to-many transform:
| |
Filtering and transforming at once
Since flat_map’s closure can return an empty iterator, it naturally combines filtering and mapping — just return None or Some:
| |
This works because Option implements IntoIterator — Some(x) yields one item, None yields zero. It’s equivalent to filter_map, but flat_map generalizes to any iterator, not just Option.
Traversing nested structures
Got a tree-like structure? flat_map lets you drill into children naturally:
| |
flat_map vs map + flatten
They’re semantically identical — flat_map(f) is just map(f).flatten(). But flat_map reads better and signals your intent: “each element produces multiple items, and I want them all in one sequence.”
| |
flat_map has been stable since Rust 1.0 — it’s a fundamental iterator combinator that replaces nested loops with clean, composable pipelines.