Rust Reference ยท Iterators
Iterator filter_map, flat_map and flatten
Reference for Iterator::filter_map, flat_map and flatten in Rust: dropping None values, one-to-many mapping, flattening Option and Result, with examples.
filter_map fuses a map and a filter into one step: the closure returns an Option<B>, Some(b) values are yielded and None values are dropped. It is the idiomatic way to parse a list and silently skip what does not parse.
flat_map handles one-to-many transformations: the closure returns something iterable and all the pieces are concatenated into one stream. flatten does the concatenation alone, for an iterator whose items are already iterable (Vec<Vec<T>>, Option<T>, Result<T, E>).
let nums: Vec<i32> = ["1", "x", "3"].iter().filter_map(|s| s.parse().ok()).collect(); // [1, 3]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where F: FnMut(Self::Item) -> Option<B>; fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where U: IntoIterator, F: FnMut(Self::Item) -> U; fn flatten(self) -> Flatten<Self> where Self::Item: IntoIterator;
| Name | Description |
|---|---|
f (filter_map) |
Returns Some(value) to yield value or None to skip the item. |
f (flat_map) |
Returns any IntoIterator; all of its items are yielded in order. |
Returns: a lazy adapter. flat_map(f) is exactly map(f).flatten(), and filter_map(f) is map(f).flatten() when f returns an Option.
Usage notes
- Errors are hidden by
filter_map(|s| s.parse().ok()). It is right when bad input should be ignored. When bad input is a bug,collect::<Result<Vec<_>, _>>()reports the first error instead (seecollect). flattenremoves exactly one level. AVec<Vec<Vec<T>>>needs two calls.OptionandResultare iterators of 0 or 1 items, so flattening a stream of them keeps theSome/Okpayloads. This is the shortest way to "keep the successes".- Lazy and cheap.
flat_mapruns the inner iterator one item at a time; it does not collect the inner iterables first. It is double-ended when both the outer and inner iterators are. - Capturing the outer variable inside a nested
flat_mapneedsmoveon the inner closure (see the pairs example), otherwise the borrow ends too early. - Do not use
flat_mapwhen the closure returns a plainOption.filter_mapstates the intent better, although the result is identical. - No size information:
size_hintof these adapters has a lower bound of 0, so they are notExactSizeIterator.