Iterators

flat_map()

The .flat_map() adapter maps each element of an iterator to an IntoIterator (such as a Vec<T>, slice, range, or Option<T>) and flattens the resulting nested iterators into a single continuous sequence.

Signature

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where
    Self: Sized,
    U: IntoIterator,
    F: FnMut(Self::Item) -> U,

Calling iter.flat_map(f) is equivalent to calling iter.map(f).flatten().

Source:   [ "a b",          "c d e"          ]
              │                │       .flat_map(|s| s.split_whitespace())
              ▼                ▼
Nested:   [ ["a", "b"],     ["c", "d", "e"]  ]
              │   │           │    │    │  (flattened lazily)
              ▼   ▼           ▼    ▼    ▼
Output:   [  "a", "b",       "c", "d", "e"   ]

Expanding One Element into Zero, One, or Many Elements

Because U: IntoIterator can yield any number of elements (0, 1, or $N$), .flat_map() is the general-purpose 1-to-$N$ transformation adapter:

fn main() {
    let sentences = ["rust iterators", "are", "zero cost"];

    // Each `&str` expands into an iterator of whitespace-separated words:
    let words: Vec<&str> = sentences
        .into_iter()
        .flat_map(str::split_whitespace)
        .collect();

    println!("Words: {words:?}");
}
Words: ["rust", "iterators", "are", "zero", "cost"]

Generating Cartesian Ranges or Repeated Sequences

fn main() {
    let counts = [1_u32, 3, 2];

    // Expands each n into the range `1..=n`:
    let expanded: Vec<u32> = counts
        .into_iter()
        .flat_map(|n| 1..=n)
        .collect();

    println!("Expanded ranges: {expanded:?}");
}
Expanded ranges: [1, 1, 2, 3, 1, 2]

Borrowing Note When Returning References from .flat_map()

The IntoIterator returned by the .flat_map() closure cannot borrow a local variable created inside the closure body, because that local variable is dropped as soon as the closure returns its iterator. Return either an iterator borrowing from the input reference (s.split_whitespace()) or an owned collection (Vec<T> / [T; N]) whose IntoIter owns its elements.