Answer#
A closure is written |x| x + offset. Unlike a function, it may use offset from the surrounding code. The compiler works out the least it needs: a borrow to read, a mutable borrow to change, or ownership if the closure gives the value away. That gives each closure one of three traits:
| Trait | The closure | Can be called |
|---|---|---|
Fn | only reads what it captured | any number of times |
FnMut | changes what it captured | any number of times, needs mut |
FnOnce | moves a captured value out | once |
Every Fn closure is also FnMut and FnOnce. A function that takes a closure asks for the weakest trait it can live with.
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(x)
}
fn call_once<F: FnOnce() -> String>(f: F) -> String {
f()
}
fn main() {
let offset = 10;
let add_offset = |x| x + offset; // borrows `offset`: Fn
println!("{}", apply(add_offset, 5));
let mut count = 0;
let mut tick = || {
count += 1; // changes captured state: FnMut
count
};
tick();
tick();
println!("ticks: {}", tick());
let name = String::from("Ada");
let consume = move || name; // gives the String away when called: FnOnce
println!("{}", call_once(consume));
}15
ticks: 3
AdaHow to use them#
- Pass closures to iterator methods:
.map(|x| x * 2),.filter(|x| *x > 3). - Ask for
F: Fn(i32) -> i32in your own function when the closure is called repeatedly and only reads;FnOncewhen you call it a single time. - Use
move || ...when the closure must outlive the current function, for example forthread::spawn. Without it the compiler stops with error E0373 ("closure may outlive the current function").
Common mistakes#
- Forgetting
muton a closure variable: a closure that changes captured state must itself be declaredlet mut tick = || .... - Using the captured variable after a
moveclosure took it. The closure now owns it.