Sub topic 4
Fn, FnMut and FnOnce
This chapter assumes you know ownership, borrowing, generics with trait bounds, and the basic closure syntax from earlier chapters. Here you will learn how Rust classifies closures into three traits and how to pick the right one for a function parameter.
One closure, three possible traits
Every closure gets one or more of three traits from the standard library. The compiler chooses them by looking at what the closure body does with captured values, not at how the closure is declared.
| Trait | What the body does with captures | How many times it can be called |
|---|---|---|
| `FnOnce` | Moves a captured value out (consumes it) | At least once; possibly only once |
| `FnMut` | Mutates a captured value, but does not move it out | Many times, needs `&mut` access |
| `Fn` | Only reads captured values, or captures nothing | Many times, needs only `&` access |
The traits form a hierarchy. Every Fn closure is also FnMut, and every FnMut closure is also FnOnce. So FnOnce is the most general bound, and Fn is the most restrictive for the closure but the most flexible for the caller.
Seeing each trait in code
The program below defines one closure of each kind. Each is passed to a helper that demands exactly that trait.
fn call_fn<F: Fn() -> usize>(f: F) -> usize {
f() + f()
}
fn call_fn_mut<F: FnMut()>(mut f: F) {
f();
f();
}
fn call_fn_once<F: FnOnce() -> Vec<i32>>(f: F) -> Vec<i32> {
f()
}
fn main() {
let name = String::from("rust");
let len = || name.len(); // reads only: Fn
println!("{}", call_fn(len)); // 8
let mut log: Vec<i32> = Vec::new();
call_fn_mut(|| log.push(1)); // mutates: FnMut
println!("{:?}", log); // [1, 1]
let data = vec![1, 2, 3];
let take = move || data; // returns data, so it moves it out: FnOnce
println!("{:?}", call_fn_once(take)); // [1, 2, 3]
}The last closure returns data by value. That moves the vector out of the closure, so the closure can run only once. If you tried to call it twice, the compiler would report a use of a moved value.
Choosing a bound
Use the loosest bound your function can live with. This lets callers pass the widest range of closures.
- If you call the closure exactly once, take
FnOnce. It accepts all closures. - If you call it several times and it may change state, take
FnMut. It acceptsFnandFnMutclosures. - If you call it several times, possibly from several threads at once or while holding shared references, take
Fn.
A common error
A closure that moves a value out is FnOnce only. Passing it where Fn or FnMut is expected fails to compile:
fn run_twice<F: Fn()>(f: F) {
f();
f();
}
fn main() {
let s = String::from("hi");
run_twice(move || drop(s)); // error: expected a closure that implements `Fn`,
// but this closure only implements `FnOnce`
}The fix is to change the bound to FnOnce and call it once, or to change the closure so it no longer consumes s, for example by cloning it first.
Exercise
A function takes f: F where F: FnMut() and calls f() three times. Which of these closures can you pass: (a) || println!("hi"), (b) || counter += 1 where counter is a mut i32, (c) move || drop(text) where text is a String?
Show answer
(a) and (b) work. (a) only uses shared state, so it is Fn, which is also FnMut. (b) mutates a capture, so it is FnMut. (c) moves text out of the closure when it drops it, so it is FnOnce only and the compiler rejects it.