Sub topic 9
Adapters: map, filter, enumerate, zip, take, chain
This chapter assumes you know ownership and borrowing, basic generics and trait bounds, Option, and how to use Vec and slices. It also assumes you have read the chapters on closures and on the Iterator trait, including iter, iter_mut and into_iter.
An adapter is an Iterator method that takes an iterator and returns a new iterator. It does not produce a final value. You chain adapters, then finish with a consumer such as collect or sum, which later chapters cover.
What an adapter is
Each adapter returns a struct that wraps the previous iterator. map returns std::iter::Map<I, F>, filter returns Filter<I, P>, and so on. Each struct implements Iterator itself, so it can be wrapped again.
fn main() {
let v = vec![1, 2, 3, 4];
let it = v.iter().map(|x| x * 10).filter(|x| *x > 10);
// `it` is a Filter<Map<Iter<i32>, _>, _>, not a Vec.
let out: Vec<i32> = it.collect();
println!("{:?}", out); // [20, 30, 40]
}The types nest, and the closures are part of the type. This is why the compiler can inline them later. The chapter on laziness covers when the work happens. For now, remember that building a chain does no work.
map: transform each item
map takes a closure FnMut(Self::Item) -> B and yields the closure's result for each item. The output type may differ from the input type.
fn main() {
let names = vec!["ada", "grace", "linus"];
let lengths: Vec<usize> = names.iter().map(|n| n.len()).collect();
println!("{:?}", lengths); // [3, 5, 5]
let shout: Vec<String> = names.iter().map(|n| n.to_uppercase()).collect();
println!("{:?}", shout); // ["ADA", "GRACE", "LINUS"]
}Here names.iter() yields &&str, and method calls auto-dereference, so n.len() works. When you write arithmetic on references, such as x * 10 with x: &i32, the standard library implements the operator for &i32 too, so that also works.
filter: keep some items
filter takes a predicate FnMut(&Self::Item) -> bool. The closure receives a reference to the item, because the item must still be yielded if the predicate returns true. This causes the most common type confusion with filter.
fn main() {
let v = vec![1, 2, 3, 4, 5, 6];
// v.iter() yields &i32, so filter's closure gets &&i32.
let evens: Vec<&i32> = v.iter().filter(|x| **x % 2 == 0).collect();
println!("{:?}", evens); // [2, 4, 6]
// into_iter yields i32, so filter's closure gets &i32.
let big: Vec<i32> = v.into_iter().filter(|x| *x > 3).collect();
println!("{:?}", big); // [4, 5, 6]
}You can destructure the reference in the closure parameter to avoid the stars: |&&x| x % 2 == 0 for the first case and |&x| x > 3 for the second.
filter_map and cloned
Two relatives are worth knowing. filter_map combines both steps: the closure returns Option<B>, and None values are dropped. cloned and copied turn an iterator of references into an iterator of values.
fn main() {
let inputs = ["4", "x", "10", "-"];
let numbers: Vec<i32> = inputs.iter().filter_map(|s| s.parse().ok()).collect();
println!("{:?}", numbers); // [4, 10]
let v = vec![1, 2, 3];
let owned: Vec<i32> = v.iter().copied().collect();
println!("{:?}", owned); // [1, 2, 3]
}enumerate: attach an index
enumerate wraps each item in a tuple (usize, Item), counting from zero. It replaces a manual counter variable.
fn main() {
let items = ["a", "b", "c"];
for (i, item) in items.iter().enumerate() {
println!("{}: {}", i, item);
}
}The index counts items that reach enumerate, not positions in the original collection. Order matters in a chain:
fn main() {
let v = vec![10, 20, 30, 40];
let a: Vec<(usize, &i32)> = v.iter().enumerate().filter(|(_, x)| **x > 15).collect();
println!("{:?}", a); // [(1, 20), (2, 30), (3, 40)]
let b: Vec<(usize, &i32)> = v.iter().filter(|x| **x > 15).enumerate().collect();
println!("{:?}", b); // [(0, 20), (1, 30), (2, 40)]
}Put enumerate before filter when you need original positions. Put it after when you need a running count of the survivors.
zip: walk two iterators together
zip pairs items from two iterators into tuples. It stops as soon as either side is exhausted, so the result has the length of the shorter input.
fn main() {
let names = ["ada", "grace", "linus"];
let scores = [90, 85];
let pairs: Vec<(&&str, &i32)> = names.iter().zip(scores.iter()).collect();
println!("{:?}", pairs); // [("ada", 90), ("grace", 85)]
}linus silently disappears. If a length mismatch would be a bug in your program, check the lengths before zipping. zip accepts anything that implements IntoIterator, so names.iter().zip(&scores) also works.
take: limit the count
take(n) yields at most n items and then returns None. Its main use is on iterators that never end, such as ranges without an upper bound.
fn main() {
let first_squares: Vec<u64> = (1..).map(|n| n * n).take(5).collect();
println!("{:?}", first_squares); // [1, 4, 9, 16, 25]
}This works because adapters are lazy: (1..) is never fully produced. The companion skip(n) discards the first n items. Together they give you a window: .skip(10).take(5).
chain: one iterator after another
chain yields every item of the first iterator, then every item of the second. Both must have the same Item type.
fn main() {
let head = vec![1, 2];
let tail = vec![3, 4];
let all: Vec<i32> = head.iter().chain(tail.iter()).copied().collect();
println!("{:?}", all); // [1, 2, 3, 4]
let with_edges: Vec<i32> = std::iter::once(0)
.chain(head.iter().copied())
.chain(std::iter::once(99))
.collect();
println!("{:?}", with_edges); // [0, 1, 2, 99]
}std::iter::once creates a one-item iterator, which is handy for adding a single element at either end.
Combining adapters
Adapters compose in the order you write them. Each item flows through the whole chain before the next item starts, rather than each adapter processing the whole collection in turn.
fn main() {
let result: Vec<(usize, u32)> = (1u32..)
.filter(|n| n % 2 == 0)
.map(|n| n * n)
.take(3)
.enumerate()
.collect();
println!("{:?}", result); // [(0, 4), (1, 16), (2, 36)]
}Common errors
| Symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| `expected &i32, found i32` in `filter` | The predicate receives `&Item`, so `iter()` gives `&&i32` | Dereference twice or destructure with `\ | &&x\ | ` |
| Chain compiles but prints nothing | No consumer ended the chain | Add `collect`, `sum`, or a `for` loop | ||
| `chain` type mismatch | One side yields `&i32`, the other `i32` | Add `.copied()` or `.cloned()` to one side | ||
| Missing items after `zip` | The shorter iterator ended first | Compare lengths first if equal length is required | ||
| Unexpected indexes | `enumerate` placed after `filter` | Move `enumerate` earlier |
Exercises
Exercise
What does this code print, and why? let v = vec![5, 6, 7, 8]; let r: Vec<(usize, i32)> = v.into_iter().filter(|x| x % 2 == 0).enumerate().collect(); println!("{:?}", r);
Show answer
It prints [(0, 6), (1, 8)]. The filter keeps 6 and 8, and enumerate runs after the filter, so it numbers the survivors starting at 0.
Exercise
Write an expression that takes the vectors a = vec![1, 2, 3] and b = vec![10, 20, 30, 40] and produces a Vec<i32> of the sums of matching positions, followed by the number 0 at the end.
Show answer
a.iter().zip(b.iter()).map(|(x, y)| x + y).chain(std::iter::once(0)).collect::<Vec<i32>>() gives [11, 22, 33, 0]. zip stops after three pairs because a is shorter, and once(0) appends the final element.