Sub topic 12
Lifetimes with Box<dyn Trait> and closures
This chapter assumes you can write generic functions and traits, you know that closures capture variables by reference or by move, and you have read the earlier chapters on lifetime annotations, elision, and T: 'a bounds. A trait object is a value of type dyn Trait used behind a pointer such as Box or &. Its concrete type is erased at compile time, and that is where the lifetime rules in this chapter come from.
The lifetime hidden inside `dyn Trait`
A Box<dyn Fn() -> usize> can hold any closure. The compiler no longer knows which closure it is, so it can't see what that closure captured. If the closure captured a reference, the box must not outlive that reference.
To track this, every trait object type carries a lifetime bound, written dyn Trait + 'a. It means that all data the concrete type contains is valid for at least 'a. You often don't write it, because the compiler fills in a default.
Default object lifetime bounds
The default depends on the pointer that wraps the trait object:
| Written type | Meaning |
|---|---|
| `Box<dyn Trait>` | `Box<dyn Trait + 'static>` |
| `&'a dyn Trait` | `&'a (dyn Trait + 'a)` |
| `&'a mut dyn Trait` | `&'a mut (dyn Trait + 'a)` |
| `Box<dyn Trait + 'a>` | as written |
Box has no lifetime parameter, so a bare dyn Trait inside it defaults to 'static. A reference &'a already supplies a lifetime, so the trait object reuses it. These defaults apply in type signatures and struct fields. Inside function bodies, the compiler infers the lifetime instead.
The first row causes most of the errors people hit.
The classic error: a boxed closure that borrows
This function captures a borrowed &str in a boxed closure and returns it:
// Does not compile.
fn make_len_fn(s: &str) -> Box<dyn Fn() -> usize> {
Box::new(move || s.len())
}The return type means Box<dyn Fn() -> usize + 'static>. The closure holds s, whose lifetime is only the caller's borrow. The compiler reports a "lifetime may not live long enough" error, saying the returned value requires the borrow to outlive 'static. The error does not point at dyn at all, so it is easy to misread.
You have two correct fixes. Which one you pick depends on whether the closure should own its data or borrow it.
Fix 1: bound the trait object by the input lifetime
Say that the box lives no longer than the borrow:
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 caller can use f only while text is alive. This costs nothing at runtime. It adds a restriction, and the lifetime parameter spreads into any struct or function that stores or passes the box.
Fix 2: use the anonymous lifetime `'_`
When elision can pick the lifetime, '_ shortens the signature. With one input lifetime, the output lifetime is that same lifetime, and this includes the bound on a trait object:
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 signature as Fix 1. Use '_ when elision would work anyway, and a named lifetime when you need to relate several parameters.
Fix 3: own the data
If the closure should outlive the input, copy what it needs into the closure. The 'static default then holds without changes:
fn make_len_fn(s: &str) -> Box<dyn Fn() -> usize> {
let owned = s.to_owned();
Box::new(move || owned.len())
}
fn main() {
let f = {
let temp = String::from("short-lived");
make_len_fn(&temp)
};
println!("{}", f());
}Here f is used after temp is dropped, which Fixes 1 and 2 would reject. The cost is an allocation and a copy.
Choosing between borrowing and owning
The move keyword does not decide this. move only changes how the closure captures: by value instead of by reference. If the captured value is a &str, moving it copies the reference, and the closure still depends on the original data. What matters is the type of the captured value. A reference carries a lifetime, and a String does not.
<br>
Trait objects in structs
A struct field of type Box<dyn Fn()> is 'static by default, so the struct can't hold a closure that borrows. To allow borrowing, add a lifetime parameter and put it on the trait object:
use std::cell::Cell;
struct Button<'a> {
label: &'a str,
on_click: Box<dyn Fn() + 'a>,
}
fn main() {
let name = String::from("OK");
let clicks = Cell::new(0);
let button = Button {
label: &name,
on_click: Box::new(|| clicks.set(clicks.get() + 1)),
};
(button.on_click)();
(button.on_click)();
println!("{} clicked {} times", button.label, clicks.get());
}The closure borrows clicks without move. That is allowed because the trait object is bounded by 'a, and 'a is no longer than the borrow of clicks. With Box<dyn Fn()> instead, the compiler would reject the closure, because it would have to outlive 'static.
A Vec of such boxes works the same way:
fn adders<'a>(offset: &'a i32) -> Vec<Box<dyn Fn(i32) -> i32 + 'a>> {
vec![
Box::new(move |x| x + *offset),
Box::new(move |x| x * *offset),
]
}
fn main() {
let off = 10;
let fs = adders(&off);
for f in &fs {
println!("{}", f(2));
}
}This prints 12 and 20.
References to trait objects
For &dyn Trait parameters, the default rule &'a (dyn Trait + 'a) usually does what you want:
fn call_twice(f: &dyn Fn() -> i32) -> i32 {
f() + f()
}
fn main() {
let base = 21;
println!("{}", call_twice(&|| base));
}The closure borrows base, and the reference to it is short-lived, so no annotations are needed. The 'static default applies only to the owned Box form.
`impl Trait` as an alternative
If you don't need to store closures of different types in one collection, impl Fn avoids boxing. It also needs a lifetime bound when it captures a reference:
fn make_len_fn(s: &str) -> impl Fn() -> usize + '_ {
move || s.len()
}
fn main() {
let text = String::from("hello");
println!("{}", make_len_fn(&text)());
}Use Box<dyn ...> when the concrete types differ at runtime (for example, a Vec of different closures). Use impl Trait when there is one concrete type and you want static dispatch.
`'static` bounds on spawned work
The same distinction appears in std::thread::spawn, which requires the closure to be 'static. A closure that borrows a local variable is rejected. You can move owned data into the closure, or use scoped threads, which guarantee that the threads end before the borrow does:
use std::thread;
fn main() {
let data = vec![1, 2, 3];
thread::scope(|s| {
s.spawn(|| println!("len = {}", data.len()));
});
println!("still usable: {:?}", data);
}Remember that T: 'static does not mean the value lives forever. It means the type contains no non-'static references, so owned values like String satisfy it.
Closure parameters and higher-ranked bounds
Inside dyn Fn(&str) -> &str, the elided lifetimes are higher-ranked. That type means dyn for<'x> Fn(&'x str) -> &'x str. The closure must work for every input lifetime, and the output is tied to the input. The next chapter covers for<'a> in more detail. For now, you only need to know that the + 'a bound on the trait object and the lifetimes inside the Fn(...) signature are separate things. The first says how long the closure itself may be used, and the second describes the references passed in and out when it is called.
Common mistakes
- Expecting
moveto remove the borrow. Moving a&strinto a closure still ties the closure to the string's lifetime. - Reading the error as being about
Box. The message usually mentions'staticor "captured variable cannot escape". Look for adyn Traitwithout a+ 'abound. - Adding
+ 'aeverywhere. If a closure only uses owned data, the default'staticis the most flexible choice for callers. - Putting
'staticon a parameter to silence an error. That restricts callers to owned values or literals. A named lifetime is usually the correct fix.
Exercise
This function fails to compile. Explain why, then give two different fixes. fn greeter(name: &str) -> Box<dyn Fn() -> String> { Box::new(move || format!("Hello, {name}")) }
Show answer
The return type defaults to Box<dyn Fn() -> String + 'static>, but the closure captures the borrowed name, so it cannot be 'static. Fix 1: bound the trait object by the borrow, either fn greeter<'a>(name: &'a str) -> Box<dyn Fn() -> String + 'a> or fn greeter(name: &str) -> Box<dyn Fn() -> String + '>. Fix 2: own the data with let name = name.toowned(); and keep the 'static return type.
Exercise
In struct Task { run: Box<dyn Fn()> }, can you build a Task whose closure borrows a local variable? What change makes it possible?
Show answer
No. The field type is Box<dyn Fn() + 'static>, which rejects closures that borrow locals. Add a lifetime parameter and write struct Task<'a> { run: Box<dyn Fn() + 'a> }. A Task can then hold a closure that borrows a local, and the Task cannot outlive that local.