Sub topic 9
Closures as dyn Fn
This chapter assumes you know how generics and trait bounds work, how Box<dyn Trait> is built and used, and that dyn Trait calls go through a vtable. It applies those ideas to closures, which is where most Rust programmers first need trait objects.
Every closure has its own type
A closure is a value of an anonymous struct that the compiler generates. The struct holds the captured variables, and the compiler implements one or more of the traits Fn, FnMut and FnOnce for it. You can't write the type's name. Two closures with identical bodies still have two different types.
That is the problem trait objects solve here. A function can return one concrete type, and a Vec can hold one element type. If the closure is chosen at runtime, or if you want a list of different closures, no single closure type fits. Box<dyn Fn(i32) -> i32> names the behavior ("takes an i32, returns an i32") instead of the concrete type.
fn make_adder(flag: bool) -> Box<dyn Fn(i32) -> i32> {
if flag {
Box::new(|x| x + 1)
} else {
Box::new(|x| x * 2)
}
}
fn main() {
let f = make_adder(true);
let g = make_adder(false);
println!("{} {}", f(10), g(10));
}This prints 11 20. Both branches produce a Box<dyn Fn(i32) -> i32>, so the if expression has one type. The compiler coerces each Box<closure> into a Box<dyn Fn> by pairing the data pointer with a vtable for that closure type.
If you change the return type to impl Fn(i32) -> i32, the function no longer compiles. The compiler reports mismatched types in the two branches and notes that no two closures have the same type. impl Trait in return position means "one concrete type that I don't name". It does not mean "any type that implements the trait".
The three closure traits
Which trait you put after dyn decides how the closure can be called.
| Trait | Call takes | Can be called | Typical closure |
|---|---|---|---|
| `Fn` | `&self` | Many times, also through a shared reference | Reads captured values only |
| `FnMut` | `&mut self` | Many times, needs mutable access | Changes a captured counter or buffer |
| `FnOnce` | `self` | Once, because the call consumes the closure | Moves a captured value out |
The traits form a hierarchy. Every Fn is also FnMut, and every FnMut is also FnOnce. A closure that only reads its captures can therefore be used where any of the three is expected. When you pick a bound, choose the weakest one your code needs. A parameter typed Box<dyn FnOnce()> accepts the most closures. A parameter typed Box<dyn Fn()> accepts the fewest.
The compiler picks the traits a closure implements by looking at what its body does with the captures. The move keyword changes only how values are captured, by moving them into the closure. It does not change which traits the closure implements. A move closure that only reads its captured String is still Fn.
Storing callbacks in a collection
A typical use is a registry of callbacks that run later. Each handler may capture different state, so the field type has to be a trait object.
struct Button {
handlers: Vec<Box<dyn FnMut(&str)>>,
}
impl Button {
fn new() -> Self {
Button { handlers: Vec::new() }
}
fn on_click(&mut self, f: impl FnMut(&str) + 'static) {
self.handlers.push(Box::new(f));
}
fn click(&mut self, who: &str) {
for h in self.handlers.iter_mut() {
h(who);
}
}
}
fn main() {
let mut b = Button::new();
let mut count = 0;
b.on_click(move |who| {
count += 1;
println!("{who} clicked, count = {count}");
});
b.on_click(|who| println!("hello {who}"));
b.click("ann");
b.click("bob");
}The output is:
ann clicked, count = 1
hello ann
bob clicked, count = 2
hello bobSeveral details in this code are worth noting.
- The public method takes
impl FnMut(&str) + 'static, which is a generic parameter, and then boxes it. Callers pass a plain closure and never writeBox::new. The generic is used once, at the boundary, and is erased when the value is stored. - The
+ 'staticbound is required here.Box<dyn FnMut(&str)>in a struct field meansBox<dyn FnMut(&str) + 'static>, so the boxed closure may not borrow from the stack. - The first closure is
move, socountis copied into the closure. The closure keeps its owncountbetween calls, which is why the output shows 1 and then 2. The outercountstays at 0. clicktakes&mut selfbecause calling anFnMutneeds mutable access to each handler.
Calling a boxed FnOnce
A FnOnce call takes self by value. For a trait object that means moving a value of unknown size out of a box. Rust supports this for Box<dyn FnOnce>, so you can call it directly.
fn main() {
let name = String::from("report");
let task: Box<dyn FnOnce() -> String> = Box::new(move || name + ".txt");
println!("{}", task());
}The closure moves name out of its own captures when it runs, so it can run only once. A second call to task() is a compile error because the first call consumed the box. Job queues and thread pools use Box<dyn FnOnce() + Send + 'static> for exactly this reason, because each job runs a single time.
Borrowing closures and lifetimes
The 'static default for a boxed trait object surprises people the first time a closure captures a reference. If the trait object must hold a borrow, say so with a lifetime bound.
fn make_greeter<'a>(prefix: &'a str) -> Box<dyn Fn(&str) -> String + 'a> {
Box::new(move |name| format!("{prefix} {name}"))
}
fn main() {
let p = String::from("hi");
let g = make_greeter(&p);
println!("{}", g("sam"));
}The + 'a tells the compiler that the closure may not outlive the prefix it borrows. Without it, the function fails with an error saying the captured reference must outlive 'static. Lifetimes in trait object types get their own chapter later. For closures, remember two rules. A boxed closure that stores a borrow needs an explicit + 'a. A &dyn Fn parameter has its lifetime inferred from the reference.
Passing closures without boxing
A trait object doesn't always need a Box. When a function only calls the closure and doesn't keep it, a reference is enough.
fn apply_twice(f: &dyn Fn(i32) -> i32, x: i32) -> i32 {
f(f(x))
}
fn apply_twice_generic<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(f(x))
}
fn main() {
let offset = 3;
println!("{}", apply_twice(&|x| x + offset, 1));
println!("{}", apply_twice_generic(|x| x + offset, 1));
}Both calls print 7. The generic version is compiled once per closure type, so the compiler can inline the closure body into the loop. The &dyn Fn version is compiled once and calls through the vtable. For a hot inner loop the generic version is usually faster. For a function called rarely, or one that sits in a large library where code size matters, the &dyn Fn version avoids duplicated machine code. The dyn version also works recursively without the compiler having to instantiate an unbounded chain of types.
Function pointers are a separate type
fn(i32) -> i32 (lowercase fn) is a function pointer. It is a plain, sized, Copy value that holds only a code address. It is not a trait object.
- A closure that captures nothing coerces to a function pointer.
- Function pointers implement
Fn,FnMutandFnOnce, so a function pointer can be passed wherever a closure bound is expected, and can be boxed asBox<dyn Fn>. - A closure that captures anything can't coerce to a function pointer, because there is nowhere to store the captures.
Use fn types when you want to forbid captures, or when you interoperate with C. Use dyn Fn for everything else.
Cost and choosing a form
A boxed closure costs one heap allocation, one pointer indirection on each call, and no inlining across the call. A closure with no captures is zero-sized, and Box::new of a zero-sized value does not allocate. The vtable call is cheap, but it blocks optimizations that would otherwise fold the closure into its caller.
As a rule of thumb:
- For a parameter that is only called, use a generic
F: Fn(...)orimpl Fn(...). - For a function that returns exactly one closure, return
impl Fn(...). - Use
Box<dyn Fn...>when the closure is stored in a struct field, kept in a collection, or chosen among several at runtime. - Choose
Fn,FnMutorFnOnceby what the caller will do with the closure, not by what is easiest to type.
Common errors
- Mismatched types in
if/matcharms. Each arm returns a different closure type. Box each one and annotate the result asBox<dyn Fn...>. - "Cannot borrow as mutable" when calling. The closure is
FnMut, but the binding or the reference isn't mutable. Declare itlet mut for iterate withiter_mut(). - "Closure may outlive the current function". A boxed closure defaults to
'staticand captures a local by reference. Addmove, or add an explicit+ 'abound. - "Cannot move out of ... which is behind a shared reference". A closure that consumes its captures is
FnOnceonly, and you tried to call it through&or as aFn. Change the bound toFnOnce, or clone the captured value inside the closure. - Spawning a thread with a boxed closure.
Box<dyn Fn()>isn'tSend. WriteBox<dyn Fn() + Send>, as the next chapters on auto traits explain.
Exercise
A function pick(flag: bool) -> impl Fn(i32) -> i32 returns |x| x + 1 in one branch and |x| x - 1 in the other. It does not compile. Why, and what is the smallest change to the signature and the branches that fixes it?
Show answer
impl Fn stands for one hidden concrete type, but the two closures have two different anonymous types, so the branches don't agree. Change the return type to Box<dyn Fn(i32) -> i32> and wrap each closure in Box::new(...). Both branches then have the same type.
Exercise
You store jobs as Vec<Box<dyn FnOnce() -> u32>>. Write the loop that runs every job and sums the results. Why is for job in jobs.iter() the wrong way to write it?
Show answer
Use let total: u32 = jobs.into_iter().map(|job| job()).sum();, or for job in jobs { total += job(); }. Calling a FnOnce consumes the box, so the loop must own each job. iter() yields &Box<dyn FnOnce()>, and a shared reference can't be consumed, so the call doesn't compile.