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.
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..=10)is the source: the numbers from 1 to 10 inclusive.filter(|n| n % 3 == 0)keeps the numbers divisible by 3:3,6and9.collect()gathers them into a vector, and[3, 6, 9]is printed.v.iter().map(|x| x * 2)doubles each item of the vector.- 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 = ….
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.
1fn main() {2 let v = vec![1, 2, 3];3 let big = v4 .iter()5 .map(|x| {6 println!("map {x}");7 x * 108 })9 .filter(|x| {10 println!("filter {x}");11 *x > 1012 });13 println!("built");14 let total: i32 = big.sum();15 println!("total {total}");16}
The chain is built, but no closure has been called yet.
So, step by step through the trace:
- The lines with
mapandfilteronly built the iteratorbigand printed nothing. - The line
builtappeared first. - The closures started working when
sumbegan asking for items. - Each item passed
mapand thenfilterbeforemaptook 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:
fn main() {
let v = vec![1, 2, 3];
let doubled = v.iter().map(|x| x * 2).collect(); // ✗
println!("{doubled:?}");
}error[E0283]: type annotations neededThe 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
mapandfilteradapters build a new iterator, and thesumandcollectconsuming methods take the items and return a result. filterkeeps the items for which the closure returnedtrue; the closure gets a reference to the item.collectandsumneed a result type:let v: Vec<i32>,let total: i32;sumtakes the iterator by value and needs nomut.- Adapters are lazy: the
mapclosure runs only when a consuming method asks for the next item, and items go down the chain one at a time.