Sub topic 4
Fn, FnMut and FnOnce
This chapter assumes you know how closures capture variables by shared borrow, mutable borrow, or move. It also assumes you can read generic functions with trait bounds like F: Fn(i32) -> i32. Here you will learn how the compiler assigns each closure to one or more of three traits, and how to choose the right trait for your own functions.
Three traits, three ways of calling
Every closure has its own unnamed type. The compiler automatically implements up to three traits for that type: Fn, FnMut and FnOnce. You cannot implement them by hand on stable Rust. You only choose which of them to require.
| Trait | How the call borrows the closure | Can be called | Typical body |
|---|---|---|---|
| `Fn` | `&self` | Any number of times, even through a shared reference | Only reads captured values |
| `FnMut` | `&mut self` | Any number of times, needs exclusive access | Mutates captured values |
| `FnOnce` | `self` | At most once, because the call consumes the closure | Moves a captured value out |
The traits form a chain. Fn requires FnMut, and FnMut requires FnOnce. So every closure is callable as FnOnce, and a closure that only reads its captures satisfies all three bounds.
The body decides, not the capture keyword
A common misunderstanding is that move makes a closure FnOnce. It does not. The compiler picks the traits by what the closure body does with each captured value:
- If the body moves a captured value out (returns it, passes it by value to a function that is not
Copy, or drops it), the closure is onlyFnOnce. - Otherwise, if the body mutates a captured value, the closure is
FnMutand alsoFnOnce. - Otherwise the closure is
Fn,FnMutandFnOnce.
An Fn closure
This closure only reads greeting, so you can call it repeatedly. You can still use greeting afterwards because the closure only borrowed it.
fn main() {
let greeting = String::from("hello");
let shout = || println!("{}!", greeting.to_uppercase());
shout();
shout();
println!("{}", greeting);
}An FnMut closure
This closure changes log, so the closure variable must be declared mut. Calling it needs &mut access to the closure itself.
fn main() {
let mut log: Vec<String> = Vec::new();
let mut record = |msg: &str| log.push(msg.to_string());
record("start");
record("stop");
println!("{:?}", log);
}An FnOnce closure
This closure returns the captured String, which moves it out of the closure. After one call, the closure no longer owns anything to return.
fn main() {
let name = String::from("Ada");
let consume = move || name;
let owned = consume();
println!("{}", owned);
}If you tried consume() a second time, the compiler would reject it with a "use of moved value" error. The call consume() takes self, so the first call used up the closure. The error notes that the closure cannot be invoked more than once because it moves a variable out of its environment.
move does not change the trait
A move closure takes ownership of its captures, but if the body only reads them, the closure is still Fn.
fn main() {
let label = String::from("id");
let show = move || println!("{}", label);
show();
show();
}Here label lives inside the closure. Printing it only borrows it, so the closure can be called repeatedly. The same holds for Copy captures such as integers. Moving a Copy value out of a closure copies it, and the closure stays Fn.
Choosing a bound in your own functions
The bound you write is a promise about how your function calls the closure. It also decides which callers can use your function.
- Require
FnOnceif you call the closure at most once. This accepts the widest range of closures, including ones that move captures out. - Require
FnMutif you call it several times and don't need to share it across calls or threads. This acceptsFnandFnMutclosures. - Require
Fnonly if you must call it through a shared reference, for example when several parts of your code or several threads call it at the same time. This accepts the fewest closures.
fn call_once<F: FnOnce() -> String>(f: F) -> String {
f()
}
fn call_twice<F: FnMut()>(mut f: F) {
f();
f();
}
fn call_many<F: Fn(i32) -> i32>(f: F) -> i32 {
f(1) + f(2)
}
fn main() {
let s = String::from("owned");
println!("{}", call_once(move || s));
let mut n = 0;
call_twice(|| n += 10);
println!("{}", n); // 20
let k = 5;
println!("{}", call_many(|x| x * k)); // 15
}Note mut f in call_twice. Calling an FnMut needs &mut f, so the parameter binding must be mutable. Forgetting this gives an error that you "cannot borrow f as mutable".
Rule of thumb
Start with the loosest bound your function body allows: try FnOnce, then FnMut, then Fn. The compiler tells you when the body calls the closure more often than the bound permits.
What the standard library asks for
The standard library follows the same rule. Looking at these bounds helps you predict which closures work.
| API | Bound | Why |
|---|---|---|
| `Option::unwrap_or_else` | `FnOnce` | Called at most once, only if the value is `None` |
| `std::thread::spawn` | `FnOnce + Send + 'static` | The new thread runs the closure once |
| `Iterator::map`, `filter`, `for_each` | `FnMut` | Called once per item, so state can change between calls |
| `slice::sort_by_key` | `FnMut` | Called many times during the sort |
An iterator adapter that takes FnMut allows a closure with a counter. It does not require one, so a stateless Fn closure works as well.
Reusing a closure you pass by reference
Passing a closure by value moves it into the function, so you cannot use it again. If you want to keep the closure, pass a reference. A &F is Fn when F is Fn, and a &mut F is FnMut when F is FnMut.
fn run<F: FnMut()>(mut f: F) {
f();
}
fn main() {
let mut hits = 0;
let mut bump = || hits += 1;
run(&mut bump);
run(&mut bump);
println!("{}", hits); // 2
}Each call to run takes a temporary mutable borrow of bump. The borrow ends when run returns, so the second call is allowed.
Function items and pointers
Named functions also satisfy these bounds. A plain fn item that captures nothing implements Fn, FnMut and FnOnce. A function pointer such as fn(i32) -> i32 does too. A non-capturing closure can be coerced to a function pointer.
fn double(x: i32) -> i32 {
x * 2
}
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(x)
}
fn main() {
println!("{}", apply(double, 4)); // 8
println!("{}", apply(|x| x + 1, 4)); // 5
let pointer: fn(i32) -> i32 = |x| x - 1;
println!("{}", apply(pointer, 4)); // 3
}A closure that captures a variable cannot become a fn pointer, because a pointer has nowhere to store the captured data.
Common errors
- "expected a closure that implements
Fn, but this closure only implementsFnMut" orFnOnce. Your closure body does more than the bound allows. Loosen the bound (FntoFnMut), or change the body. For example, call.clone()instead of moving a value out. - Use of a moved value after calling a closure. The closure is
FnOnceand the call consumed it. Either call it once, or stop moving captured values out. - "cannot borrow as mutable" on a closure variable. Declare the closure with
let mutand the parameter withmut f. - Cannot use the captured variable while the closure is alive. An
FnMutclosure holds a mutable borrow until its last use. Readingcountbetween two calls toincis an error, but reading it after the last call is fine.
Exercises
Exercise
A closure is declared as let f = move || drop(data); where data is a Vec<i32>. Which of Fn, FnMut and FnOnce does it implement, and why?
Show answer
Only FnOnce. The body passes data by value to drop, which moves it out of the closure. After one call the closure has nothing left to give, so it cannot be called again. The move keyword is not the reason. The body is.
Exercise
You are writing fn retry<F: ???>(mut f: F) that calls f() up to three times until it returns true. Callers want to pass a closure that increments a counter. Which bound should replace ???, and why not Fn or FnOnce?
Show answer
FnMut() -> bool. The function calls the closure several times, which rules out FnOnce. The caller's closure mutates a counter, so it is not Fn, and an Fn bound would reject it. FnMut accepts both mutating closures and read-only ones.