Sub topic 13
Putting Closures and Iterators Together
This chapter assumes you know closure capture modes, the Fn, FnMut and FnOnce traits, the difference between iter, iter_mut and into_iter, and the basic adapters and consumers. Here you combine them into pipelines and see how closure capture affects the whole chain.
Closures are the arguments of every pipeline
Most iterator methods take a closure. The method's trait bound decides what the closure may do with captured variables.
| Method | Closure bound | What it means for captures |
|---|---|---|
| `map`, `for_each`, `fold` | `FnMut` | May mutate captured state |
| `filter`, `take_while` | `FnMut(&Item) -> bool` | Receives a reference to each item |
| `any`, `all`, `find` | `FnMut` | Runs only until the answer is known |
Because these bounds are FnMut, a pipeline closure can read captured values, update them, or both. It cannot move a captured value out, because that would make it FnOnce.
A worked pipeline
This program totals order amounts per customer. Small orders are filtered out using a captured threshold.
use std::collections::HashMap;
struct Order {
customer: &'static str,
cents: u32,
}
fn main() {
let orders = vec![
Order { customer: "ana", cents: 1200 },
Order { customer: "bo", cents: 300 },
Order { customer: "ana", cents: 800 },
Order { customer: "cy", cents: 2500 },
];
let min = 500;
let mut totals: HashMap<&str, u32> = HashMap::new();
orders
.iter()
.filter(|o| o.cents >= min)
.for_each(|o| *totals.entry(o.customer).or_insert(0) += o.cents);
let mut rows: Vec<_> = totals.into_iter().collect();
rows.sort();
println!("{:?}", rows); // [("ana", 2000), ("cy", 2500)]
}The filter closure borrows min immutably. The for_each closure borrows totals mutably, so it is FnMut. Both borrows end when the chain finishes. That is why totals.into_iter() works on the next line.
Fallible steps with filter_map and `?`
filter_map expects a closure that returns Option. Inside such a closure, ? returns None early from the closure, not from main. This lets you drop bad input without a separate filter step.
use std::collections::HashMap;
fn main() {
let lines = ["a=1", "b=2", "bad", "c=x"];
let parsed: HashMap<&str, i32> = lines
.iter()
.filter_map(|l| {
let (k, v) = l.split_once('=')?;
Some((k, v.parse().ok()?))
})
.collect();
println!("{}", parsed.len()); // 2
println!("{}", parsed["a"]); // 1
}The type annotation on parsed drives inference. It tells collect to build a HashMap and tells parse to produce an i32.
Common errors in combined code
- Reference levels.
iter()yields&T, andfilterpasses&&T. Write|o| o.cents >= minand let auto-deref work, or pattern match with|&&x|forCopytypes. - Borrow conflicts. A closure that mutably captures
totalsholds that borrow while the chain runs. Readingtotalsinside another closure in the same chain fails to compile. - Unused lazy chains. A chain with no consumer does nothing. The compiler warns that iterators are lazy and do nothing unless consumed.
- Moving captured values. Calling
into_iter()on a capturedVecinsidemapmakes the closureFnOnce, andmaprejects it. Borrow the vector or clone it instead.
Exercise
Given let v = vec![1, 2, 3, 4, 5, 6]; let limit = 3;, write one iterator chain that produces the sum of the squares of the items greater than limit. What value does it give, and which captured variable does the closure borrow?
Show answer
let total: i32 = v.iter().filter(|&&x| x > limit).map(|x| x * x).sum(); The items 4, 5 and 6 pass the filter, so the sum is 16 + 25 + 36 = 77. The filter closure borrows limit immutably.