Sub topic 6
Returning closures with impl Fn and Box<dyn Fn>
This chapter assumes you know how closures capture variables (borrow, mutable borrow, move), the Fn, FnMut and FnOnce traits, and basic generics and trait bounds. It also assumes you know what Box is. You will learn how to return closures from functions, which return type to pick, and what each choice costs.
Why you cannot name a closure's type
Every closure has its own unnamed type, generated by the compiler. Two closures with identical bodies and signatures still have different types. Because you cannot write that type in a function signature, you describe the closure by what it can do. Rust gives you two ways to do that:
impl Fn(...) -> ...says "some single concrete type that implements this trait". The compiler knows the type, so calls are static.Box<dyn Fn(...) -> ...>says "some heap-allocated value of any type that implements this trait". The concrete type is erased, and calls go through a vtable.
A bare dyn Fn(i32) -> i32 cannot be returned directly. It is not Sized, so the compiler cannot reserve stack space for it. That is why it must sit behind a pointer such as Box.
Returning impl Fn
Use impl Fn when the function always returns the same closure expression. The trait you pick (Fn, FnMut or FnOnce) is what the caller is allowed to do with the result.
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n
}
fn make_counter() -> impl FnMut() -> u32 {
let mut count = 0;
move || {
count += 1;
count
}
}
fn make_greeter(name: String) -> impl FnOnce() -> String {
move || name
}
fn main() {
let add10 = make_adder(10);
println!("{}", add10(5)); // 15
let mut counter = make_counter();
let first = counter();
let second = counter();
println!("{} {}", first, second); // 1 2
let greet = make_greeter(String::from("Ada"));
println!("{}", greet()); // Ada
}Notice three details:
make_counterreturnsimpl FnMut, so the caller must bind the result withlet mut. The closure ownscount, and each call changes it.make_greeterreturnsimpl FnOnce. The closure movesnameout as its return value, so it can run only once. Declaring itFnwould not compile.- Every closure here uses
move. See the next section for why.
Why move is nearly always required
A returned closure outlives the function that created it. Without move, a closure that uses a local variable only borrows it, and that local is dropped when the function returns. The compiler rejects this with error E0373, "closure may outlive the current function, but it borrows n". The fix is move, which copies or moves the captured values into the closure.
The one-type limit of impl Fn
impl Fn stands for exactly one concrete type chosen inside the function. If an if or match returns a different closure in each branch, the function fails to compile, even when the closures have the same signature. The compiler reports "if and else have incompatible types", because the two closure types differ.
Box<dyn Fn> removes the limit. Both closures are coerced to the same trait object type, so the branches agree.
fn make_op(name: &str) -> Option<Box<dyn Fn(i32, i32) -> i32>> {
match name {
"add" => Some(Box::new(|a: i32, b: i32| a + b)),
"mul" => Some(Box::new(|a: i32, b: i32| a * b)),
_ => None,
}
}
fn main() {
for name in ["add", "mul", "pow"] {
match make_op(name) {
Some(op) => println!("{}: {}", name, op(6, 7)),
None => println!("{}: unknown", name),
}
}
}This prints add: 13, mul: 42 and pow: unknown. The same trick lets you store different closures in one collection or one struct field.
fn main() {
let offset = 8;
let steps: Vec<Box<dyn Fn(i32) -> i32>> = vec![
Box::new(|x: i32| x + 1),
Box::new(|x: i32| x * 10),
Box::new(move |x: i32| x - offset),
];
let result = steps.iter().fold(4, |acc, f| f(acc));
println!("{}", result); // 42
}Each element has a different underlying closure type, but all of them are Box<dyn Fn(i32) -> i32>, so they fit in one Vec.
Comparing the two options
| Row | `impl Fn(...)` | `Box<dyn Fn(...)>` |
|---|---|---|
| Dispatch | Static, can be inlined | Dynamic, through a vtable |
| Allocation | None for the closure itself | One heap allocation |
| Different closures per branch | Not allowed | Allowed |
| Storable in `Vec` or struct field with mixed closures | No | Yes |
| Type visible to the compiler | Yes | Erased |
In practice, start with impl Fn. Switch to Box<dyn Fn> when the compiler tells you the types differ or when you need a heterogeneous collection. The cost of boxing is one allocation plus an indirect call. That cost is small, but it prevents inlining in hot loops.
Composing closures
Generic code can build new closures out of existing ones. Because compose always returns a single closure expression, impl Fn is enough.
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
move |x| g(f(x))
}
fn main() {
let inc_then_double = compose(|x: i32| x + 1, |x: i32| x * 2);
println!("{}", inc_then_double(4)); // 10
}The move here transfers f and g into the returned closure. Without it, the closure would borrow two parameters that die at the end of compose.
Returned closures that borrow
A returned closure can hold a reference, but then its lifetime is tied to that reference. Name the lifetime and add it to the return type with + 'a.
fn make_prefixer<'a>(prefix: &'a str) -> impl Fn(&str) -> String + 'a {
move |s| format!("{prefix}{s}")
}
fn main() {
let p = String::from("log: ");
let log = make_prefixer(&p);
println!("{}", log("started")); // log: started
}The move keyword copies the reference prefix into the closure. It does not copy the string. The closure is valid only while p is alive.
A boxed trait object has the same rule, with a different default. Box<dyn Fn(&str) -> String> in a return position means Box<dyn Fn(&str) -> String + 'static>, so it cannot hold a non-static borrow. Write Box<dyn Fn(&str) -> String + 'a> to allow one.
Common errors
- E0373, closure may outlive the current function. You forgot
move. Add it. - "
ifandelsehave incompatible types". You returned different closures throughimpl Fn. Box them and annotate the return type, or box each branch withas Box<dyn Fn(i32) -> i32>. - "cannot borrow as mutable". You returned an
FnMutclosure and bound it withoutmut. Writelet mut f = make_counter();. - "closure cannot be invoked more than once". The closure moves a captured value out, so it is
FnOnce. Clone the value inside the closure, or accept being called once. - "the size for values of type
dyn Fncannot be known". You wrote-> dyn Fn(i32) -> i32without a pointer. UseBox<dyn Fn(i32) -> i32>.
Exercise
The function below fails to compile. Why, and how do you fix it without changing the call sites? fn pick(double: bool) -> impl Fn(i32) -> i32 { if double { |x| x * 2 } else { |x| x + 1 } }
Show answer
Each closure has its own unique type, and impl Fn can stand for only one concrete type, so the two branches disagree. Change the return type to Box<dyn Fn(i32) -> i32> and wrap each closure in Box::new: if double { Box::new(|x: i32| x * 2) } else { Box::new(|x: i32| x + 1) }. Callers still call the result as pick(true)(5).
Exercise
Write a function make_accumulator(start: i32) that returns a closure which adds its argument to a running total and returns the new total. Which return type do you use, and does the caller need mut?
Show answer
Return impl FnMut(i32) -> i32, with the body let mut total = start; move |n| { total += n; total }. The closure mutates its captured state, so it is FnMut, and the caller must write let mut acc = make_accumulator(0);.