Sub topic 1
Rust Closures and Iterators: Functional Patterns Without the Overhead
Prerequisites
This chapter assumes Rust basics, ownership, borrowing, references, generics, trait bounds, and Option and Result.
Closure syntax: anonymous functions that remember things
A closure is an anonymous function value. It can capture variables from the scope where it is created.
fn main() {
let factor = 3;
let scale = |x: i32| x * factor;
println!("{}", scale(4)); // 12
}The |x: i32| part lists the parameter, and the expression after it is the body. Rust often infers parameter and return types:
let double = |x| x * 2;The compiler determines the type from how the closure is used.
How closures capture their environment
A closure captures an outer variable in the least powerful way that its body requires:
- A shared borrow reads the value.
- A mutable borrow changes the value.
- Ownership moves the value into the closure.
fn main() {
let mut count = 0;
let mut increment = || count += 1;
increment();
increment();
println!("{}", count); // 2
}The closure must be declared mut because calling it changes its captured state.
Taking ownership with `move`
The move keyword makes captured values belong to the closure. This is essential when the closure must outlive its current scope, such as when a thread runs it.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("{data:?}");
});
handle.join().unwrap();
}After the closure is created, data belongs to it and cannot be used by main.
Fn, FnMut and FnOnce
These traits describe how a closure can be called:
Fncan be called repeatedly without changing or consuming its captures.FnMutcan change captured values.FnOncemay consume a captured value and can be called at most once.
Every closure implements FnOnce. A closure that implements Fn also implements FnMut and FnOnce.
Accepting closures as arguments
Use a generic trait bound when a function accepts a closure:
fn apply_twice<F: Fn(i32) -> i32>(f: F, value: i32) -> i32 {
f(f(value))
}
fn main() {
let add_three = |x| x + 3;
println!("{}", apply_twice(add_three, 2)); // 8
}Choose FnMut when the function may mutate the closure, and FnOnce when it only needs to call a consuming closure.
Exercise
Which bound should a function use if it calls a closure repeatedly and the closure increments captured state?
Show answer
Use FnMut, and bind the closure parameter as mutable if the function calls it through a mutable local binding.