Skip to content
Tutorials Center
My learning

Topics

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.

Rust
let doubled_evens: Vec<i32> = (1..=6).filter(|n| n % 2 == 0).map(|n| n * 2).collect();
// [4, 8, 12]

Try it

Rust map and filter chained

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.

Rust Laziness and side effects

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

Rust
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". Use for, collect, sum or for_each.
  • Prefer a for loop for side effects. map with println! inside is legal but misleading; for_each or a plain loop says what you mean.
  • Closure argument shapes. iter() gives &T; into_iter() on an owned collection gives T; filter always adds one more &. Use .copied() or .cloned() before filter to work with plain values, or pattern-match with |&&x|.
  • Order matters for cost. Put filter before an expensive map to 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.
  • map does not unwrap. If the closure returns an Option or Result, you get an iterator of those. Use filter_map to drop Nones or collect into Result<Vec<_>, _>.
  • Fusing is automatic. .filter(a).filter(b) and .filter(|x| a(x) && b(x)) compile to the same loop in release builds.