Sub topic 12
Lifetimes in trait object types
This chapter assumes you know how Box<dyn Trait> and &dyn Trait work, and that you can read lifetime annotations such as 'a on functions and structs.
The hidden lifetime
A trait object type has a lifetime bound, even when you don't write one. The type dyn Greeter means "some value that implements Greeter". That value may hold references, and the compiler must know how long those references stay valid. The bound dyn Greeter + 'a says that everything inside the object is valid for at least 'a.
When you leave the bound out, the compiler fills in a default:
| Written type | Meaning |
|---|---|
| `Box<dyn Greeter>` | `Box<dyn Greeter + 'static>` |
| `Rc<dyn Greeter>`, `Arc<dyn Greeter>` | `'static` bound |
| `&'a dyn Greeter` | `&'a (dyn Greeter + 'a)` |
| `&'a mut dyn Greeter` | `&'a mut (dyn Greeter + 'a)` |
Inside a reference the default follows the reference's lifetime. Everywhere else it is 'static.
A trait object that borrows
The 'static default causes the most common error. In this example the concrete type Prefix holds a borrowed &str:
trait Greeter {
fn greet(&self) -> String;
}
struct Prefix<'a> {
text: &'a str,
}
impl<'a> Greeter for Prefix<'a> {
fn greet(&self) -> String {
format!("hello, {}", self.text)
}
}
fn boxed<'a>(text: &'a str) -> Box<dyn Greeter + 'a> {
Box::new(Prefix { text })
}
fn main() {
let name = String::from("Ada");
let g = boxed(&name);
println!("{}", g.greet());
}The return type Box<dyn Greeter + 'a> ties the boxed value to the input borrow. The box cannot outlive name, and the borrow checker enforces that.
If you wrote -> Box<dyn Greeter> instead, the compiler would read it as Box<dyn Greeter + 'static>. It would then reject Box::new(Prefix { text }), because text is not known to live for 'static. The error message mentions that the lifetime must outlive 'static, which is confusing the first time you see it.
Eliding the name
You can use the anonymous lifetime '_ when the elision rules already link input and output:
trait Greeter {
fn greet(&self) -> String;
}
struct Prefix<'a> {
text: &'a str,
}
impl<'a> Greeter for Prefix<'a> {
fn greet(&self) -> String {
format!("hello, {}", self.text)
}
}
fn boxed(text: &str) -> Box<dyn Greeter + '_> {
Box::new(Prefix { text })
}
fn main() {
let name = String::from("Grace");
println!("{}", boxed(&name).greet());
}Trait objects in structs
A struct that stores a boxed trait object needs a lifetime parameter if the object may borrow:
trait Greeter {
fn greet(&self) -> String;
}
struct Fixed;
impl Greeter for Fixed {
fn greet(&self) -> String {
String::from("hi")
}
}
struct Holder<'a> {
item: Box<dyn Greeter + 'a>,
}
fn main() {
let h = Holder { item: Box::new(Fixed) };
println!("{}", h.item.greet());
}If you write item: Box<dyn Greeter> without 'a, the struct accepts only 'static objects. That is often what you want. Owned types such as String and Vec are 'static, and so are structs that hold no references. A 'static bound does not mean the value lives forever. It means the value contains no short-lived borrows.
Exercise
A function has the signature fn make(s: &str) -> Box<dyn Greeter> and returns Box::new(Prefix { text: s }). It does not compile. Why, and what are two ways to fix it?
Show answer
Without a written bound, Box<dyn Greeter> means Box<dyn Greeter + 'static>, but Prefix borrows s, which is not 'static. One fix is to change the return type to Box<dyn Greeter + '_> (or use a named lifetime 'a), so the box is tied to the borrow of s. The other is to make Prefix own its data, for example by storing a String, so the object is 'static.