Sub topic 2
Recap: closures and the Fn trait family
This chapter reviews closures and the Fn, FnMut, and FnOnce traits. Later chapters build async closures on top of them, so the details here matter.
I assume you already know:
- Ownership, borrowing, and basic lifetimes.
- Generic functions with trait bounds.
- How to call a function that takes a closure, such as
Iterator::map.
You don't need any async knowledge for this chapter.
What a closure is
A closure is an anonymous function that can use variables from the scope where you write it. Those variables are its captures. The compiler turns each closure into a unique, unnamed struct. The struct's fields hold the captured values or references, and the closure body becomes a method on it.
Two consequences follow:
- Every closure has its own type. Two closures with identical bodies still have different types, so you name them through trait bounds, not by type.
- A closure's captures are part of its size and lifetime. A closure that holds a reference cannot outlive the thing it borrows.
fn main() {
let name = String::from("Ada");
let greet = |greeting: &str| format!("{greeting}, {name}!");
println!("{}", greet("Hello"));
println!("{}", greet("Hi"));
println!("{name}");
}Here greet captures name by shared reference, because formatting only needs to read it. You can call greet many times, and name is still usable afterwards.
How captures work
The compiler picks the weakest capture mode that the body allows, one captured variable at a time.
| Body does this with a captured value | Capture mode |
|---|---|
| Only reads it | Shared borrow (`&T`) |
| Mutates it | Mutable borrow (`&mut T`) |
| Moves it out, or consumes it | By value (`T`) |
Since Rust 2021, closures capture disjoint fields separately. A closure that uses config.name does not borrow all of config.
The move keyword changes the capture mode and nothing else. It forces every captured variable to be captured by value, even if the body only reads it. You need move when the closure must outlive the current scope, for example when you return it or send it to another thread.
The three Fn traits
The compiler gives each closure one or more of three traits. The trait depends on what the body does with its captures, not on how they were captured.
| Trait | Call signature | The body may | Callable |
|---|---|---|---|
| `FnOnce` | `call_once(self)` | Move captured values out | At least once |
| `FnMut` | `call_mut(&mut self)` | Mutate captured values | Many times, needs `&mut` access |
| `Fn` | `call(&self)` | Only read captured values | Many times, needs `&` access |
The traits form a hierarchy:
The direction can seem backwards at first. FnOnce is the weakest promise, because the caller can only call it once. Fn is the strongest, because the closure can be called any number of times, even through a shared reference. So a function that accepts FnOnce accepts every closure. A function that demands Fn accepts the fewest.
An Fn closure
The greet closure above only reads name, so it implements all three traits.
An FnMut closure
fn main() {
let mut total = 0;
let mut add = |n: i32| total += n;
add(2);
add(3);
println!("{total}");
}The body mutates total, so the closure holds a &mut i32 and implements FnMut and FnOnce, but not Fn. Calling it needs &mut self, so the binding must be declared let mut add. The mutable borrow lasts until the last use of add. That is why println!("{total}") compiles after the calls but would not compile between them.
An FnOnce closure
fn main() {
let message = String::from("done");
let consume = move || message;
let first = consume();
println!("{first}");
// consume(); // error: use of moved value: `consume`
}The body returns message by value. That moves the String out of the closure, which can happen only once. The closure implements FnOnce only. A second call would not compile, because the first call consumed the closure itself.
Accepting closures in function signatures
You accept a closure with a generic parameter and a trait bound. Pick the weakest bound that your function can work with. That gives callers the most freedom.
fn call_twice<F>(f: F) -> i32
where
F: Fn() -> i32,
{
f() + f()
}
fn call_mut_twice<F>(mut f: F)
where
F: FnMut(),
{
f();
f();
}
fn call_once<F>(f: F) -> String
where
F: FnOnce() -> String,
{
f()
}
fn main() {
let base = 20;
println!("{}", call_twice(|| base + 1));
let mut count = 0;
call_mut_twice(|| count += 1);
println!("{count}");
let owned = String::from("hello");
println!("{}", call_once(move || owned));
}Output:
42
2
helloNote three details:
call_mut_twicedeclaresmut f. Calling anFnMutneeds&mut f, so the parameter binding must be mutable.call_oncetakesfby value and consumes it. If your function calls the closure exactly once,FnOnceis the right bound.- A bound like
F: Fn()accepts function items and function pointers too, because plain functions implement theFntraits.
You can also write impl Fn() -> i32 in argument position. It is shorthand for an unnamed generic parameter.
Returning closures
A closure's type has no name, so you return it with impl Trait or a boxed trait object.
fn make_adder(k: i32) -> impl Fn(i32) -> i32 {
move |x| x + k
}
fn make_op(subtract: bool, k: i32) -> Box<dyn Fn(i32) -> i32> {
if subtract {
Box::new(move |x| x - k)
} else {
Box::new(move |x| x + k)
}
}
fn main() {
let add5 = make_adder(5);
println!("{}", add5(1));
let op = make_op(true, 3);
println!("{}", op(10));
}make_adder needs move. Without it the closure would borrow the parameter k, which dies when the function returns, and the compiler would reject it.
Use impl Fn when the function always returns the same closure. Use Box<dyn Fn> when different branches return different closures, since each closure has its own type and impl Trait allows only one. The box costs a heap allocation and a dynamic call.
Closures and lifetimes in signatures
Closure bounds have a special rule for references. Consider this bound:
fn first_word_of<F>(f: F) -> usize
where
F: Fn(&str) -> &str,
{
f("hello world").len()
}
fn main() {
let n = first_word_of(|s| s.split(' ').next().unwrap());
println!("{n}");
}The Fn(&str) -> &str sugar means "for every lifetime 'a, take &'a str and return &'a str". This is a higher-ranked bound, written for<'a> Fn(&'a str) -> &'a str. The elision rules for Fn(...) sugar tie the output lifetime to the input, as they do for ordinary functions.
The rule works only when the return type is spelled out in the bound. Suppose the signature used F: Fn(&str) -> R with R as a separate generic type. Then R is chosen once, outside the for<'a> scope, so it cannot mention the argument's lifetime. A closure that returns a borrow of its argument will not satisfy that bound.
Common errors
These are the compiler errors you will meet most often with closures.
- "cannot borrow as mutable" or "closure is
FnMut, notFn". Your closure mutates a capture but the bound saysFn. Change the bound toFnMut, or remove the mutation, for example by using aCellorMutex. - "use of moved value" on a closure. The closure moves a captured value out, so it is
FnOnceand a second call is invalid. Clone the value inside the body, or restructure so the body doesn't consume the capture. - "closure may outlive the current function". The closure borrows a local, but it is returned or sent to a thread. Add
move. - "cannot borrow
xas immutable because it is also borrowed as mutable". A liveFnMutclosure holds&mut x. Finish using the closure before touchingx, or restructure. - Two branches return "different closure types". Each closure has a unique type. Box them as
Box<dyn Fn...>or give both branches one shared function.
What comes next
Everything in this chapter assumes the closure body runs and returns a value right away. Asynchronous callbacks add a twist. The body of an async function produces a future, and that future may keep references into the closure's captures or arguments. The Fn traits you reviewed here describe how the closure itself is called, and they say nothing about the lifetime of what it returns. The next chapters show where that gap causes errors.
Exercise
What are the Fn traits of the closure move || drop(v), where v is a captured Vec<i32>? Can you pass it to a function that requires F: FnMut()?
Show answer
It implements only FnOnce. The body passes v by value to drop, which moves the vector out of the closure, so the closure can run only once. move does not matter here, because the trait depends on what the body does with the capture. It cannot be passed where FnMut is required.
Exercise
This code fails to compile. Why, and what is the smallest fix? fn calltwice<F: Fn()>(f: F) { f(); f(); } fn main() { let mut count = 0; calltwice(|| count += 1); }
Show answer
The closure mutates count, so it implements FnMut and FnOnce but not Fn, and the bound F: Fn() rejects it. Change the signature to fn call_twice<F: FnMut()>(mut f: F). The parameter must be mut because calling an FnMut needs &mut f.
Exercise
Why does fn pick(flag: bool) -> impl Fn(i32) -> i32 { if flag { |x| x + 1 } else { |x| x - 1 } } fail, and how do you fix it?
Show answer
Each closure has its own unique type, and impl Trait in return position must resolve to one concrete type. Return Box<dyn Fn(i32) -> i32> and wrap each closure with Box::new(...). A single closure that branches on flag inside its body would also work.