Sub topic 9
Adapters: map, filter, enumerate, zip, take, chain
This chapter assumes you know the Iterator trait and next, how iter() differs from into_iter(), and closure syntax. Adapters are the methods on Iterator that take one iterator and return a new one.
What an adapter does
An adapter wraps an existing iterator in a new struct that implements Iterator. It does not run anything yet. You chain adapters to describe a pipeline, then a consumer such as collect pulls items through it.
map and filter
map transforms each item. filter keeps items for which the closure returns true.
fn main() {
let nums = vec![1, 2, 3, 4, 5, 6];
let evens_squared: Vec<i32> = nums
.iter()
.filter(|n| **n % 2 == 0)
.map(|n| n * n)
.collect();
println!("{:?}", evens_squared); // [4, 16, 36]
}iter() yields &i32. filter passes its closure a reference to the item, so the closure sees &&i32, which is why it needs **n. map receives the item itself, so n is &i32, and n * n produces an i32.
enumerate and zip
enumerate pairs each item with its index, starting at 0. zip pairs items from two iterators and stops when the shorter one ends. They compose, and a nested tuple pattern unpacks the result.
fn main() {
let names = ["ann", "bo", "cy"];
let ages = [31, 25, 40];
for (i, (name, age)) in names.iter().zip(ages.iter()).enumerate() {
println!("{i}: {name} is {age}");
}
}This prints three lines, starting with 0: ann is 31.
take and chain
take(n) yields at most n items and then stops. chain yields everything from the first iterator, then everything from the second. Both iterators must have the same Item type.
fn main() {
let first = 1..=3;
let second = 10..;
let combined: Vec<i32> = first.chain(second).take(5).collect();
println!("{:?}", combined); // [1, 2, 3, 10, 11]
}The range 10.. never ends. take(5) is what makes the pipeline finish. This works only because adapters are lazy: nothing computes the infinite tail up front.
Summary of the adapters
| Adapter | Closure input | Output item |
|---|---|---|
| `map(f)` | the item | whatever `f` returns |
| `filter(p)` | `&Item` | the same item |
| `enumerate()` | none | `(usize, Item)` |
| `zip(other)` | none | `(Item, OtherItem)` |
| `take(n)` | none | the same item |
| `chain(other)` | none | the same item |
Common errors
- Unused adapter warning. A chain with no consumer does nothing. The compiler warns that iterator adaptors are lazy.
- Type mismatch in
chain. Chainingiter()(items&i32) with a range (itemsi32) fails. Convert one side, for example with.copied(). - Wrong order.
take(3).filter(...)takes three items first and then filters them.filter(...).take(3)finds three matches. The two can give different results.
Exercise
Given let v = vec![10, 20, 30, 40];, write an expression that produces a Vec<(usize, i32)> holding the index and value of each element greater than 15, but only the first two such elements. What does it return?
Show answer
v.iter().copied().enumerate().filter(|(_, x)| *x > 15).take(2).collect::<Vec<(usize, i32)>>() returns [(1, 20), (2, 30)]. enumerate runs before filter, so the indices refer to positions in the original vector, and take(2) stops the pipeline after two matches.