Sub topic 12
Lifetimes with Box<dyn Trait> and closures
This chapter assumes you know lifetime annotations on functions and structs, the 'static lifetime, and generic bounds like T: 'a. Here you will see how lifetimes attach to trait objects, and why closures that capture references need them.
The hidden bound on trait objects
A trait object such as Box<dyn Fn() -> usize> is a value whose concrete type is erased. The compiler still needs to know how long the value may live, because the erased type might contain references.
So every trait object type carries a lifetime bound. When you leave it out, the compiler fills in a default:
Box<dyn Trait>meansBox<dyn Trait + 'static>.&'a dyn Traitmeans&'a (dyn Trait + 'a).
The first default surprises people. A plain Box<dyn Fn()> can only hold values that contain no short-lived borrows.
A closure that borrows
The next function returns a closure that captures a &str. The closure holds a reference, so the trait object must not outlive that reference. You state this with + 'a.
fn make_len_fn<'a>(s: &'a str) -> Box<dyn Fn() -> usize + 'a> {
Box::new(move || s.len())
}
fn main() {
let text = String::from("hello");
let f = make_len_fn(&text);
println!("{}", f());
}The move keyword copies the reference s into the closure. The bound + 'a says the boxed closure is valid only while the borrowed data is. If text were dropped before f is called, the compiler would reject the program.
What happens without the bound
If you write the return type as Box<dyn Fn() -> usize>, the default 'static applies. The closure captures s, which has lifetime 'a, and 'a is not 'static. The compiler then reports an error that the parameter type may not live long enough, and suggests adding a lifetime bound.
You have two ways to fix this:
- Add
+ 'ato the trait object, as above. The closure may borrow. - Make the closure own its data, for example by capturing a
Stringinstead of a&str. Then'staticis satisfied.
Choose the first when you want to avoid copying. Choose the second when the closure must be stored or sent somewhere that outlives the caller.
Using the anonymous lifetime
In a signature with one input reference, you can write '_ instead of naming the lifetime. It asks the compiler to infer it by the elision rules.
fn make_len_fn(s: &str) -> Box<dyn Fn() -> usize + '_> {
Box::new(move || s.len())
}
fn main() {
let text = String::from("hello");
let f = make_len_fn(&text);
println!("{}", f());
}This is the same function as before. Elision ties '_ to the single input lifetime.
Choosing between `impl Fn` and `Box<dyn Fn>`
When you return a single closure, impl Fn() -> usize + '_ also works and avoids the heap allocation. Use Box<dyn Fn> when you need to store different closures in one collection or pick between them at runtime.
| Return type | Allocation | Can hold different closure types | Lifetime default |
|---|---|---|---|
| `Box<dyn Fn() -> usize>` | Heap | Yes | `'static` |
| `Box<dyn Fn() -> usize + 'a>` | Heap | Yes | `'a` |
| `impl Fn() -> usize + 'a` | None | No, one concrete type | You must state it |
A diagram of the relationship
Exercise
This function does not compile. Why, and what is one fix? fn prefixer(p: &str) -> Box<dyn Fn(&str) -> String> { Box::new(move |s| format!("{p}{s}")) }
Show answer
The return type defaults to Box<dyn Fn(&str) -> String + 'static>, but the closure captures p, a borrowed &str that is not 'static. One fix is to add a lifetime bound: fn prefixer<'a>(p: &'a str) -> Box<dyn Fn(&str) -> String + 'a>. Another is to make the closure own the data by calling let p = p.to_string(); before the closure and capturing that String.