Sub topic 2
Returning Closures and Building Iterator Pipelines
Assume Rust ownership, borrowing, generics, trait bounds, Option, Result, and Vec. A closure is an anonymous function that can capture values from its surrounding scope.
Returning closures with `impl Fn` and `Box<dyn Fn>`
A closure's type is anonymous, so a function cannot name it directly. Use impl Fn when one concrete closure type is returned:
fn make_adder(amount: i32) -> impl Fn(i32) -> i32 {
move |value| value + amount
}
fn main() {
let add_five = make_adder(5);
println!("{}", add_five(7)); // 12
}move transfers amount into the closure. Box<dyn Fn> is useful when different closure types must share one return type or when dynamic dispatch is acceptable.
fn make_multiplier(n: i32) -> Box<dyn Fn(i32) -> i32> {
Box::new(move |value| value * n)
}The `Iterator` trait
An iterator produces values one at a time. Its core method is next, which returns Some(item) until the sequence ends, then returns None. Adapter methods build a new iterator, while consumer methods use it.
`iter`, `iter_mut`, and `into_iter`
The choice determines what each item contains:
| Method | Item type | Effect |
|---|---|---|
| `iter()` | `&T` | Borrows items |
| `iter_mut()` | `&mut T` | Mutably borrows items |
| `into_iter()` | `T` | Moves items out |
For a Vec<T>, into_iter() consumes the vector.
Adapters and lazy evaluation
Adapters include map, filter, enumerate, zip, take, and chain. They do not run until a consumer, such as collect or sum, requests values.
fn main() {
let first = vec!["a", "bb", "ccc"];
let second = vec!["dddd", "eeeee"];
let result: Vec<(usize, usize)> = first
.iter()
.filter(|word| word.len() > 1)
.enumerate()
.zip(second.iter())
.take(1)
.chain(std::iter::once((99, &"end")))
.map(|((index, left), right)| (index, left.len() + right.len()))
.collect();
println!("{result:?}");
}The map closure runs only as collect drives the pipeline.
Exercise
Which method should you use to mutate every element of a vector without moving the vector?
Show answer
Use iter_mut(), which yields mutable references.