Sub topic 13
Putting Closures and Iterators Together
This chapter assumes you know closure capture rules, the Fn, FnMut and FnOnce traits, the Iterator trait, and the common adapters and consumers. Here you combine them. You will see what the closures in a pipeline receive, how they capture state, and where the compiler pushes back.
The shape of a pipeline
A typical pipeline has three parts:
- A source, such as
iter(),into_iter()or a range. - Zero or more adapters, each taking a closure that describes one step.
- A consumer, such as
collect,sumorfold, that drives the work.
Each item travels through the whole chain before the next item is pulled. No intermediate collection is built between steps.
Closures that capture local variables
The main benefit of pairing closures with adapters is that a step can use values from the surrounding function. A plain fn item cannot do this.
fn main() {
let min_len = 4;
let words = vec!["apple", "bob", "cat", "dodo", "emu"];
let long: Vec<String> = words
.iter()
.filter(|w| w.len() >= min_len)
.map(|w| w.to_uppercase())
.collect();
println!("{:?}", long); // ["APPLE", "DODO"]
}The filter closure borrows min_len immutably. The borrow lasts only as long as the closure, which is consumed by collect. After that line you can use min_len freely.
What each closure actually receives
The closure parameter type depends on both the adapter and the source. Mistakes here cause most "expected i32, found &i32" errors.
For v.iter() over a Vec<i32>, the iterator's Item is &i32:
| Method | Closure parameter type |
|---|---|
| `map`, `filter_map`, `for_each`, `any`, `all` | `&i32` |
| `filter`, `find`, `take_while`, `skip_while` | `&&i32` |
| `fold` | `(acc, &i32)` |
Adapters that only inspect an item, such as filter and find, pass it by reference, so you get one extra &. Closure parameters accept patterns, so you can strip the references in the signature:
fn main() {
let nums = vec![1, 2, 3, 4, 5, 6];
let squares_of_even: Vec<i32> = nums
.iter()
.filter(|&&n| n % 2 == 0)
.map(|&n| n * n)
.collect();
println!("{:?}", squares_of_even); // [4, 16, 36]
}In |&&n|, the two & patterns peel &&i32 down to n: i32. In |&n|, one & peels &i32.
Closures with mutable state
Adapters such as map, filter and for_each accept FnMut, so a closure may change captured variables. Declare the variable mut, and remember the closure holds a mutable borrow while the pipeline runs.
fn main() {
let nums = vec![1, 2, 3, 4, 5, 6];
let mut seen = 0;
let evens: Vec<i32> = nums
.iter()
.filter(|&&n| {
seen += 1;
n % 2 == 0
})
.copied()
.collect();
println!("{} {:?}", seen, evens); // 6 [2, 4, 6]
}seen can be read after collect because the closure was moved into the Filter adapter, and the adapter was consumed. If you read seen inside another closure in the same chain, the compiler would report two conflicting borrows.
State carried across items is often clearer with a dedicated tool. fold threads an accumulator through the chain, and scan does the same while yielding a value per step. Use a captured mut variable only for simple counters or logging.
Building maps with fold and collect
fold fits when the result is not a simple sum. This word counter takes the accumulator by value, changes it, and returns it:
use std::collections::HashMap;
fn main() {
let text = "the cat the dog the end";
let counts = text
.split_whitespace()
.fold(HashMap::new(), |mut m, w| {
*m.entry(w).or_insert(0) += 1;
m
});
let mut pairs: Vec<_> = counts.into_iter().collect();
pairs.sort();
println!("{:?}", pairs); // [("cat", 1), ("dog", 1), ("end", 1), ("the", 3)]
}The |mut m, w| pattern makes the accumulator mutable inside the closure only. The closure returns m, so ownership passes to the next step. We sort the pairs because HashMap iteration order is not defined.
When each item maps to one key and one value, collect into a HashMap is shorter. Pass an iterator of (K, V) tuples:
use std::collections::HashMap;
fn main() {
let names = ["ann", "bo", "cy"];
let lengths: HashMap<&str, usize> = names.iter().map(|n| (*n, n.len())).collect();
println!("{}", lengths["ann"]); // 3
}Handling failure inside a pipeline
Parsing and validation steps often fail. You have two common choices, and they mean different things.
- Skip bad items with
filter_mapand.ok(). - Stop at the first bad item by collecting into
Result<Vec<_>, _>.
fn main() {
let lines = ["10", "x", "30"];
let lenient: Vec<i32> = lines.iter().filter_map(|s| s.parse().ok()).collect();
println!("{:?}", lenient); // [10, 30]
let strict: Result<Vec<i32>, _> = lines.iter().map(|s| s.parse::<i32>()).collect();
println!("{}", strict.is_err()); // true
}The lenient version silently drops "x". Choose it only when dropping bad data is intended. The strict version surfaces the first error, which is usually safer for input you do not control.
One item, many outputs: flat_map
map produces one output per input. When a step produces zero or more outputs, use flat_map. Its closure returns anything that implements IntoIterator, and the results are joined into one stream.
fn main() {
let sentences = vec!["a b", "c", "d e f"];
let words: Vec<&str> = sentences
.iter()
.flat_map(|s| s.split(' '))
.collect();
println!("{:?}", words); // ["a", "b", "c", "d", "e", "f"]
}Returning a pipeline from a function
A function can return an unfinished pipeline as impl Iterator. The closure usually captures an argument, and that argument will not outlive the call. That is why the closure needs move.
struct Order {
id: u32,
cents: u64,
}
fn big_ids(orders: &[Order], min: u64) -> impl Iterator<Item = u32> + '_ {
orders
.iter()
.filter(move |o| o.cents >= min)
.map(|o| o.id)
}
fn main() {
let orders = vec![
Order { id: 1, cents: 250 },
Order { id: 2, cents: 900 },
Order { id: 3, cents: 500 },
];
for id in big_ids(&orders, 500) {
println!("{}", id); // 2, then 3
}
}The '_ ties the returned iterator to the borrow of orders. Without move, the closure would borrow min, a local of big_ids, and the compiler would reject returning it. Because min is Copy, move copies it and the closure owns its own value.
Common errors in combined code
| Symptom | Cause | Fix |
|---|---|---|
| `expected i32, found &i32` | `iter()` yields references | Use `copied()`, a `&n` pattern, or `*n` |
| "closure may outlive the current function" | A returned closure borrows a local | Add `move` |
| "cannot borrow `x` as mutable, also borrowed as immutable" | A pipeline over `x` has a closure that mutates `x` | Collect first, or mutate after the chain ends |
| "type annotations needed" at `collect` or `sum` | The target type is unknown | Annotate the variable or use `collect::<Vec<_>>()` |
| Nothing happens | The chain has no consumer | End with `collect`, `count`, `for_each`, and so on |
The third error deserves a closer look. If v.iter() is running, v is borrowed. A closure in that chain that pushes to v would need a second, conflicting borrow, so it fails to compile. The fix is to build the new items in a separate Vec and extend v after the chain finishes.
Exercise
Given let names = vec!["ann", "bo", "cy"]; and let min = 3;, write one pipeline that produces a Vec<String> of the uppercase names whose length is at least min. What does it return?
Show answer
let out: Vec<String> = names.iter().filter(|n| n.len() >= min).map(|n| n.to_uppercase()).collect(); The closure in filter borrows min. Only "ann" has length 3 or more, so the result is ["ANN"].
Exercise
A function fn above(v: &[i32], limit: i32) -> impl Iterator<Item = &i32> + '_ returns v.iter().filter(|&&n| n > limit). Why does it fail to compile, and what is the one-word fix?
Show answer
The closure borrows limit, a local parameter that is dropped when the function returns, so the returned iterator would hold a dangling reference. Writing move |&&n| n > limit copies limit into the closure and fixes it.