Sub topic 6
Returning closures with impl Fn and Box<dyn Fn>
This chapter assumes you know how closures capture variables, what move does, and how Fn, FnMut and FnOnce differ. It also assumes basic generics and trait bounds.
Why you cannot name a closure's type
Every closure has its own unique type that the compiler generates. You cannot write that type in a function signature. To return a closure, you describe it by the trait it implements. Rust gives you two ways to do this: impl Fn and Box<dyn Fn>.
Returning with impl Fn
impl Fn(i32) -> i32 in return position means "some single concrete type that implements Fn(i32) -> i32". The compiler knows the real type, so calls are static and can be inlined.
The closure usually needs move. Without it, the closure would borrow n, which is a local variable that is dropped when the function returns.
Returning with Box<dyn Fn>
Box<dyn Fn(i32) -> i32> is a trait object. The closure is stored on the heap, and calls go through a vtable (a table of function pointers). This costs one allocation and an indirect call. In exchange, the function can return different closure types under the same signature.
fn apply_twice<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(f(x))
}
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n
}
fn make_boxed(n: i32) -> Box<dyn Fn(i32) -> i32> {
Box::new(move |x| x * n)
}
fn main() {
let add5 = make_adder(5);
println!("{}", apply_twice(add5, 1)); // 11
let triple = make_boxed(3);
println!("{}", triple(7)); // 21
}make_adder(5) returns a closure that adds 5. Applying it twice to 1 gives 11. make_boxed(3) returns a boxed closure, and calling it with 7 gives 21.
Choosing between them
| Need | Use |
|---|---|
| One closure type, best speed | `impl Fn` |
| Different closures chosen at runtime | `Box<dyn Fn>` |
| A `Vec` of different closures | `Vec<Box<dyn Fn(i32) -> i32>>` |
| Closure that mutates its state | `impl FnMut` or `Box<dyn FnMut>` |
| Closure callable only once | `impl FnOnce` or `Box<dyn FnOnce>` |
Common error: two closures, one impl Fn
Two closures have two different types, even when their code is identical. This function does not compile:
fn pick(double: bool) -> impl Fn(i32) -> i32 {
if double {
|x| x * 2
} else {
|x| x + 1
}
}The compiler reports mismatched types in the if and else branches. Box both branches to fix it:
fn pick(double: bool) -> Box<dyn Fn(i32) -> i32> {
if double {
Box::new(|x| x * 2)
} else {
Box::new(|x| x + 1)
}
}
fn main() {
println!("{}", pick(true)(10)); // 20
println!("{}", pick(false)(10)); // 11
}Exercise
Why does a function with return type impl Fn(i32) -> i32 fail to compile when one branch returns |x| x + 1 and another returns |x| x - 1? What is the smallest change that fixes it?
Show answer
Each closure expression has its own distinct anonymous type, and impl Fn stands for exactly one concrete type. The two branches return different types. 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
Why does fn bad(n: i32) -> impl Fn(i32) -> i32 { |x| x + n } fail, and how do you fix it?
Show answer
Without move, the closure borrows n, a local that is dropped when bad returns, so the closure would hold a dangling reference. Write move |x| x + n so the closure owns a copy of n.