Sub topic 12
Lifetimes in trait object types
This chapter assumes you know what dyn Trait is, how Box<dyn Trait> and &dyn Trait work, and the basics of lifetimes such as &'a str and struct S<'a>. Here you will see that every trait object type carries a hidden lifetime, how the compiler picks it, and how to override it when the default is wrong.
The hidden lifetime
A trait object can wrap any concrete type that implements the trait. That type may hold references. The compiler must know how long those references stay valid, so a trait object type always has a lifetime bound. You write it as dyn Trait + 'a.
You usually don't write it, because the compiler fills in a default. The default is a common source of confusing errors, because it is sometimes 'static when you expected something shorter.
The default rules
When you write dyn Trait without a lifetime, the compiler picks the bound from context.
| What you write | What the compiler reads |
|---|---|
| `Box<dyn Trait>` | `Box<dyn Trait + 'static>` |
| `Rc<dyn Trait>`, `Arc<dyn Trait>` | `dyn Trait + 'static` |
| `&'a dyn Trait` | `&'a (dyn Trait + 'a)` |
| `&'a mut dyn Trait` | `&'a mut (dyn Trait + 'a)` |
| `Ref<'a, dyn Trait>` | `Ref<'a, dyn Trait + 'a>` |
| `trait Trait: 'a`, then `Box<dyn Trait>` | `dyn Trait + 'a` |
Two ideas sit behind the table:
- If the trait object sits inside a type that already has a lifetime bound, such as a reference
&'a, the object takes that lifetime. - If neither the trait nor the containing type gives a bound, the default is
'static.
This applies to types you write in signatures, struct fields, and type aliases. Inside a function body, the compiler infers lifetimes as it does for any other type, so a local let b: Box<dyn Trait> = ... is not forced to 'static.
A lifetime bound of 'static does not mean the value lives forever. It means the concrete type contains no non-'static references. A String, a Vec<u8>, or a struct of owned fields all satisfy it.
When the default is too strict
Consider a type that borrows a string.
trait Greeter {
fn greet(&self) -> String;
}
struct Borrowed<'a> {
name: &'a str,
}
impl<'a> Greeter for Borrowed<'a> {
fn greet(&self) -> String {
format!("hi {}", self.name)
}
}
fn boxed<'a>(name: &'a str) -> Box<dyn Greeter> {
Box::new(Borrowed { name })
}This does not compile. The return type Box<dyn Greeter> means Box<dyn Greeter + 'static>, but Borrowed<'a> only lives as long as 'a. The compiler reports that the lifetime 'a may not live long enough, and it often suggests adding a bound to the return type.
The fix is to say what you mean:
trait Greeter {
fn greet(&self) -> String;
}
struct Borrowed<'a> {
name: &'a str,
}
impl<'a> Greeter for Borrowed<'a> {
fn greet(&self) -> String {
format!("hi {}", self.name)
}
}
fn boxed<'a>(name: &'a str) -> Box<dyn Greeter + 'a> {
Box::new(Borrowed { name })
}
fn main() {
let owned = String::from("Ana");
let g = boxed(&owned);
println!("{}", g.greet());
}This prints hi Ana. The returned box cannot outlive owned, and the signature now says so. The caller's borrow checker enforces it.
The + 'a is part of the type, so it can appear anywhere a type can: return types, arguments, fields, and type aliases.
References: the default usually works
For references the default is already the shorter lifetime, so borrowed data works without extra syntax.
trait Greeter {
fn greet(&self) -> String;
}
struct Borrowed<'a> {
name: &'a str,
}
impl<'a> Greeter for Borrowed<'a> {
fn greet(&self) -> String {
format!("hi {}", self.name)
}
}
fn describe(g: &dyn Greeter) {
println!("{}", g.greet());
}
fn main() {
let owned = String::from("Ben");
let b = Borrowed { name: &owned };
describe(&b);
}Here &dyn Greeter expands to &'a (dyn Greeter + 'a). The Borrowed<'_> value only needs to outlive the reference, and it does.
This is why &dyn Trait parameters rarely cause trouble, while Box<dyn Trait> in struct fields and return types does.
Trait objects in structs
A struct field of type Box<dyn Fn(i32) -> i32> requires a 'static closure. A closure that borrows a local variable cannot go in it. To allow borrowing, give the struct a lifetime parameter and put it on the trait object.
struct Handler<'a> {
callback: Box<dyn Fn(i32) -> i32 + 'a>,
}
fn main() {
let offset = 5;
let h = Handler {
callback: Box::new(|x| x + offset),
};
println!("{}", (h.callback)(10));
}This prints 15. The closure borrows offset, so Handler<'a> cannot outlive offset. If you write the field as Box<dyn Fn(i32) -> i32>, the compiler reports that offset does not live long enough, because the closure must be 'static.
A move closure that captures only owned or Copy values is 'static. In that case you do not need the lifetime parameter.
Collections and mutable references
A lifetime bound is part of the element type, so it matters when you pass collections around. A function that adds borrowed values to a list must say that the list's trait objects can hold those borrows.
trait Greeter {
fn greet(&self) -> String;
}
struct Borrowed<'a> {
name: &'a str,
}
impl<'a> Greeter for Borrowed<'a> {
fn greet(&self) -> String {
format!("hi {}", self.name)
}
}
fn add<'a>(list: &mut Vec<Box<dyn Greeter + 'a>>, name: &'a str) {
list.push(Box::new(Borrowed { name }));
}
fn main() {
let a = String::from("Ana");
let b = String::from("Ben");
let mut list: Vec<Box<dyn Greeter + '_>> = Vec::new();
add(&mut list, &a);
add(&mut list, &b);
for g in &list {
println!("{}", g.greet());
}
}This prints hi Ana and hi Ben. If the parameter were &mut Vec<Box<dyn Greeter>>, the element type would be dyn Greeter + 'static, and push would reject the borrowed value. A &mut reference is invariant in its target type, so the compiler cannot shorten 'static to a smaller lifetime behind it. The caller's list would otherwise end up holding a short-lived value in a slot that promised 'static.
The '_ in main asks the compiler to infer the lifetime, which is a convenient way to write a bound you do not need to name.
Traits with their own lifetime bounds
A trait can require its implementors to satisfy a bound. Then the bound is part of every trait object of that trait.
trait Component: 'staticmeans every implementor is'static, anddyn Componentis'staticeverywhere. This is whydyn Anyis always'static:Anyhas a'staticsupertrait. It is also why downcasting withAnycan't work on types that borrow.trait Source<'a>: 'aties the object to the parameter'a. The default fordyn Source<'a>becomesdyn Source<'a> + 'a.
If you implement methods directly on a trait object, the same defaults apply. impl dyn Greeter { ... } is for dyn Greeter + 'static only. To cover shorter lifetimes, write impl<'a> dyn Greeter + 'a { ... }.
Common errors
- "Lifetime may not live long enough" on a returned
Box<dyn Trait>. The concrete type borrows from an argument. Add+ 'ato the return type, or make the value own its data. - "Borrowed value does not live long enough" with a closure in a struct. The field type is
'staticby default. Add a lifetime parameter and+ 'a, or use amoveclosure with owned captures. - A
&mut Vec<Box<dyn Trait>>parameter that rejects borrowed items. The inner type defaults to'staticand is invariant behind&mut. Give the element type the lifetime:Box<dyn Trait + 'a>. - Writing
+ 'staticeverywhere "to be safe". It makes the type stricter, not safer, and it rejects values that borrow. Use the shortest lifetime your code actually needs.
Exercise
A function is declared as fn make<'a>(s: &'a str) -> Box<dyn Fn() -> usize> and its body returns Box::new(|| s.len()). The compiler rejects it. Explain why, and write the corrected signature.
Show answer
The return type Box<dyn Fn() -> usize> defaults to Box<dyn Fn() -> usize + 'static>. The closure captures s, a reference with lifetime 'a, so it is not 'static. The signature must carry the lifetime: fn make<'a>(s: &'a str) -> Box<dyn Fn() -> usize + 'a>. An alternative is to compute let n = s.len(); first and return Box::new(move || n). That closure owns a usize, so it is 'static and the original signature works.
Exercise
Given fn show(g: &dyn Greeter) and fn keep(g: Box<dyn Greeter>), which one accepts a Borrowed<'a> value that holds a reference to a local String, and why?
Show answer
Only show accepts it. &dyn Greeter expands to &'a (dyn Greeter + 'a), so the object may borrow data that lives at least as long as the reference. Box<dyn Greeter> expands to Box<dyn Greeter + 'static>, which rejects a type that borrows a local. To make keep accept it, change the parameter to Box<dyn Greeter + 'a> with a lifetime parameter 'a on the function.