Sub topic 2
Recap: closures and the Fn trait family
This chapter assumes you know basic ownership and borrowing, can write generic functions with trait bounds, and have seen async fn and .await. It refreshes how closures work, because async closures are built on the same ideas.
What a closure is
A closure is an anonymous function that can use variables from the scope where it is written. Those variables are its captures.
Every closure has its own unique, unnamed type. You can't write that type down, so you accept closures through generics or impl Trait, with a trait bound that describes how the closure may be called.
Three traits, three ways to call
The compiler looks at what the closure body does with each captured variable. It then implements the most permissive trait that is still correct.
| Trait | Call receiver | Closure body does | How often it can be called |
|---|---|---|---|
| `Fn` | `&self` | Only reads captures | Many times, even concurrently |
| `FnMut` | `&mut self` | Mutates captures | Many times, one at a time |
| `FnOnce` | `self` | Moves a capture out | At most once |
The traits form a chain. Every Fn closure is also FnMut, and every FnMut closure is also FnOnce. A function that asks for FnOnce accepts the widest range of closures. A function that asks for Fn accepts the fewest.
Seeing the three traits in code
Each helper below uses the loosest bound that its call pattern allows.
fn call_fn<F: Fn() -> usize>(f: F) -> usize {
f() + f()
}
fn call_mut<F: FnMut()>(mut f: F) {
f();
f();
}
fn call_once<F: FnOnce() -> String>(f: F) -> String {
f()
}
fn main() {
let name = String::from("ferris");
let total = call_fn(|| name.len());
println!("{total}");
let mut count = 0;
call_mut(|| count += 1);
assert_eq!(count, 2);
let owned = call_once(move || name);
println!("{owned}");
}The first closure only reads name, so it is Fn. The second changes count, so it is FnMut, and the parameter must be declared mut f to call it. The third returns name by value, which moves it out of the closure, so it is only FnOnce.
Common mistakes
- Thinking
movepicks the trait.movecontrols how a closure captures: by value instead of by reference. The trait depends on what the body does. Amoveclosure that only reads its captures is stillFn. - Forgetting
muton the parameter. Calling anFnMutneeds a mutable binding, so writemut f: F. - Calling a
FnOncetwice. The first call consumes the closure, and the compiler reports "use of moved value". - Over-constraining a bound. Ask for
FnOnceif you call the closure once. Ask forFnMutif you call it in a loop. UseFnonly when you need to share the closure or call it from several places at once.
Why this matters for async
An async closure is still a closure. It will have the same three flavors of access to its captures, and Rust gives them matching traits: AsyncFn, AsyncFnMut, and AsyncFnOnce. The question "does the call read, mutate, or consume the captures?" carries over directly. The new part is that the call returns a future. That future may need to keep borrowing the captures while it runs, which ordinary Fn signatures cannot express. The next chapters build on this.
Exercise
Which of the traits Fn, FnMut, and FnOnce does the closure move || drop(v) implement, where v is a Vec<i32> it captured? Explain why.
Show answer
Only FnOnce. The body passes v to drop by value, which moves it out of the closure's captured state. After one call the closure no longer owns v, so it can't be called again, and Fn and FnMut would both require repeatable calls.
Exercise
A function takes f: impl Fn() and you pass || counter += 1, where counter is a local i32. Why does this fail, and what is the smallest fix?
Show answer
The closure mutates counter, so it is only FnMut, and Fn cannot be satisfied. Change the bound to impl FnMut() and declare the parameter as mut f.