Sub topic 9
Closures as dyn Fn
This chapter assumes you know the Fn, FnMut and FnOnce closure traits, Box, and the basics of dyn Trait from earlier chapters.
Why closures need dyn
Every closure has its own unnamed type, even when two closures have identical signatures. A closure is therefore a good fit for generics. It is a poor fit when one place in your code must hold or return closures that differ at runtime.
impl Fn(i32) -> i32 stands for one concrete type. A function that returns it cannot choose between two closure bodies, because the two closures are different types. Box<dyn Fn(i32) -> i32> fixes this. The closure is stored on the heap, and the caller sees only a fat pointer to "something callable with this signature".
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. The Fn traits are ordinary traits, so dyn Fn(i32) -> i32 is a normal trait object. The call f(10) goes through the vtable like any other dynamic call.
Storing many closures
The same idea lets you keep a list of different closures, such as a processing pipeline:
fn main() {
let offset = 5;
let steps: Vec<Box<dyn Fn(i32) -> i32>> = vec![
Box::new(|x| x + 1),
Box::new(move |x| x * offset),
Box::new(|x| x - 3),
];
let result = steps.iter().fold(2, |acc, f| f(acc));
println!("{}", result);
}The value goes 2, then 3, then 15, then 12, so the program prints 12. The move keyword copies offset into the second closure. The closure then owns its captured data, which matters for the lifetime rule below.
Choosing Fn, FnMut or FnOnce
The trait you put after dyn decides how callers may use the box.
| Type | Call syntax | Can mutate captures | Callable |
|---|---|---|---|
| `Box<dyn Fn()>` | `f()` | No | Many times, through `&self` |
| `Box<dyn FnMut()>` | `f()` on a `mut` binding | Yes | Many times, through `&mut self` |
| `Box<dyn FnOnce()>` | `f()` consumes the box | Yes | Once |
Use the most permissive trait that your caller needs. A closure that only reads its captures implements all three, so Fn is the most restrictive for the closure author. A stateful closure needs FnMut:
fn main() {
let mut count = 0;
let mut tick: Box<dyn FnMut() -> u32> = Box::new(move || {
count += 1;
count
});
println!("{} {}", tick(), tick());
}This prints 1 2. The binding tick must be mut, because each call needs &mut access to the closure's state.
Lifetimes and bounds
A Box<dyn Fn()> in a struct field or return type defaults to Box<dyn Fn() + 'static>. A closure that borrows a local variable does not satisfy 'static. Either move the data into the closure, or write the lifetime explicitly, for example Box<dyn Fn() + '_> in a function signature. In the same way, add + Send when the closure will cross threads: Box<dyn Fn() + Send>.
Generics or boxes for closures
If a function takes one closure and calls it, prefer F: Fn(i32) -> i32 or impl Fn(i32) -> i32. The compiler can inline the call and no allocation is needed. Use Box<dyn Fn> when you must:
- return different closures from one function,
- store closures of different types in one collection or field,
- keep a type name short, for example in a struct with many callback fields.
Exercise
Why does a function with return type impl Fn(i32) -> i32 fail to compile if one branch returns |x| x + 1 and the other returns |x| x * 2? What return type fixes it?
Show answer
impl Fn(i32) -> i32 names exactly one concrete type, and each closure has its own distinct type, so the two branches disagree. Returning Box<dyn Fn(i32) -> i32> and boxing each closure hides the concrete types behind one trait object type.