Skip to content
Theory · Closures and iterators · lesson 6 of 7

map, filter, collect

In the previous lesson boxes rode along a conveyor belt, and a worker at the end took them off one at a time. Now let's put stations on the belt. One station repaints each box, another knocks the unsuitable ones off the belt.

The key point of this picture: the stations stand idle until the worker at the end reaches for the next box. Only then does the belt move, and the box passes the stations one after another.

Adapters and consuming methods

An adapter is a method that takes an iterator and returns a new iterator that transforms the items. It is a station on the belt. A consuming method takes the iterator's items and returns a result: a number or a collection. It is the worker at the end of the belt.

You read a chain from left to right: the source, then the adapters, and one consuming method at the end. Adapters take closures: the closure tells the station what to do with each item.

The map and filter adapters

map

map calls the closure for each item and passes on what the closure returned. map(|x| x * 2) doubles each number.

filter

filter keeps the items for which the closure returned true and throws the rest away. The closure of filter only looks at an item, so it gets a reference to it, &i32. Arithmetic like n % 3 works with a reference too, but a comparison with a number needs a star: *x > 25.

Rust
fn main() {
    let v: Vec<i32> = (1..=10).filter(|n| n % 3 == 0).collect();
    println!("{v:?}"); // [3, 6, 9]
    let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
    println!("{doubled:?}"); // [6, 12, 18]
}

Let's walk through the example line by line:

  1. (1..=10) is the source: the numbers from 1 to 10 inclusive.
  2. filter(|n| n % 3 == 0) keeps the numbers divisible by 3: 3, 6 and 9.
  3. collect() gathers them into a vector, and [3, 6, 9] is printed.
  4. v.iter().map(|x| x * 2) doubles each item of the vector.
  5. The second collect() gives [6, 12, 18].

The consuming methods collect and sum

collect gathers the items into a collection. It can build different collections, so you have to name the result type: let v: Vec<i32> = ….

sum adds up all the items. It needs a result type too: let total: i32 = ….

Rust
fn main() {
    let v = vec![1, 2, 3];
    let it = v.iter().map(|x| x * 10);
    let total: i32 = it.sum();
    println!("{total}"); // 60
}

it has no mut, even though items are taken out of the iterator. sum takes the whole iterator, by value, and calls next inside itself. The variable it itself does not change, and after sum it is no longer available.

Laziness

map computes nothing by itself. It only builds a new iterator that holds the source iterator and the closure. The closure runs when a consuming method asks for the next item. If there is no such method, the compiler warns: unused `Map` that must be used, and adds iterators are lazy and do nothing unless consumed.

When a consuming method does ask for items, the chain works item by item: the first item passes all the stations, then the second, and so on. Step through the program and watch two things: built is printed before everything else, and map and filter take turns item by item.

LiveA lazy chainstep 1 of 10 · frames: 1

The chain is built, but no closure has been called yet.

Watch when the map and filter closures run

So, step by step through the trace:

  1. The lines with map and filter only built the iterator big and printed nothing.
  2. The line built appeared first.
  3. The closures started working when sum began asking for items.
  4. Each item passed map and then filter before map took the next one.

In JavaScript, map on an array is eager: it walks all the items at once and builds a new array. In Rust adapters are lazy, and interviewers like to ask about it: "What does a chain with a println! inside map print?"

Common mistake

collect was called without saying what to collect into:

Rust
fn main() {
    let v = vec![1, 2, 3];
    let doubled = v.iter().map(|x| x * 2).collect(); // ✗
    println!("{doubled:?}");
}
TEXT
error[E0283]: type annotations needed

The program does not compile. collect can build different collections, and from this line the compiler cannot tell which one you need. The fix is to name the type on the variable, let doubled: Vec<i32> = …, or on the call itself: collect::<Vec<i32>>().

Key points

  • The map and filter adapters build a new iterator, and the sum and collect consuming methods take the items and return a result.
  • filter keeps the items for which the closure returned true; the closure gets a reference to the item.
  • collect and sum need a result type: let v: Vec<i32>, let total: i32; sum takes the iterator by value and needs no mut.
  • Adapters are lazy: the map closure runs only when a consuming method asks for the next item, and items go down the chain one at a time.