Rust Reference ยท Iterators
Iterator map and filter
Reference for Iterator::map and Iterator::filter in Rust: lazy adapters, closure argument types (&&x patterns), chaining, and common mistakes.
map and filter are the two most-used iterator adapters. map(f) applies a closure to every item and yields the results. filter(p) keeps only the items for which the predicate returns true. Both return a new iterator and do nothing until something consumes it.
The one thing that trips people up is the argument type of filter. Its closure receives a reference to the item (&Self::Item), because the item still has to be passed on if it is kept. Iterating &[i32] gives &i32 items, so the filter closure sees &&i32, which is why you will write patterns like |&&x| or |x| **x > 3.
let doubled_evens: Vec<i32> = (1..=6).filter(|n| n % 2 == 0).map(|n| n * 2).collect(); // [4, 8, 12]
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 map<B, F>(self, f: F) -> Map<Self, F> where F: FnMut(Self::Item) -> B; fn filter<P>(self, predicate: P) -> Filter<Self, P> where P: FnMut(&Self::Item) -> bool;
| Name | Description |
|---|---|
f |
For map: takes each item by value and returns the new value. May be FnMut, so it can keep state. |
predicate |
For filter: takes a reference to each item and returns true to keep it. |
Returns: a lazy adapter (Map or Filter) that is itself an Iterator.
Edge cases: the length of a Map equals the length of its source, so it stays ExactSizeIterator and double-ended. A Filter has an unknown length: size_hint is (0, Some(upper)).
Usage notes
- Nothing runs without a consumer. Calling
v.iter().map(...)on its own produces the warning "iterators are lazy and do nothing unless consumed". Usefor,collect,sumorfor_each. - Prefer a
forloop for side effects.mapwithprintln!inside is legal but misleading;for_eachor a plain loop says what you mean. - Closure argument shapes.
iter()gives&T;into_iter()on an owned collection givesT;filteralways adds one more&. Use.copied()or.cloned()beforefilterto work with plain values, or pattern-match with|&&x|. - Order matters for cost. Put
filterbefore an expensivemapto skip work on rejected items. - Method references work:
.map(str::len),.map(String::from),.map(i32::abs),.filter(char::is_ascii_digit)(takes&char, which matches). Closures are needed when types differ. mapdoes not unwrap. If the closure returns anOptionorResult, you get an iterator of those. Usefilter_mapto dropNones orcollectintoResult<Vec<_>, _>.- Fusing is automatic.
.filter(a).filter(b)and.filter(|x| a(x) && b(x))compile to the same loop in release builds.