Sub topic 11
Lifetime bounds on generic types
This chapter assumes you can write generic functions and structs with trait bounds, and that you can read 'a annotations on functions and structs. It covers what T: 'a means and when you need to write it.
What a lifetime bound says
A generic type T can be anything, including a type that contains references. A lifetime bound limits that. T: 'a reads "T outlives 'a". Every reference stored inside T must stay valid for at least 'a.
Types with no references inside satisfy every lifetime bound. i32 and String are examples. Only types that borrow can fail one.
Bounds on structs
Suppose a struct holds a &'a T. The struct is only valid if T itself lives as long as 'a, so the bound T: 'a must hold.
use std::fmt::Display;
struct Wrapper<'a, T> {
inner: &'a T,
}
impl<'a, T: Display> Wrapper<'a, T> {
fn show(&self) -> String {
format!("[{}]", self.inner)
}
}
fn main() {
let n = 42;
let w = Wrapper { inner: &n };
println!("{}", w.show());
}Older Rust required you to write struct Wrapper<'a, T: 'a>. Since Rust 1.31 the compiler infers T: 'a from the field &'a T. You still see the explicit form in older code, and it is harmless.
Bounds you must write: `T: 'static`
Some APIs cannot know how long the data will be used, so they demand the longest possible lifetime. std::thread::spawn is the usual case. The new thread may run after the calling function returns, so the data it takes cannot borrow from the caller.
use std::fmt::Debug;
use std::thread;
fn run_in_thread<T: Debug + Send + 'static>(value: T) {
thread::spawn(move || println!("{value:?}")).join().unwrap();
}
fn main() {
run_in_thread(String::from("owned"));
run_in_thread(vec![1, 2, 3]);
run_in_thread("literal");
}All three calls compile. The String and the Vec own their data, and the literal is a &'static str.
This call would not compile:
let s = String::from("borrowed");
run_in_thread(&s); // error[E0597]: `s` does not live long enoughHere T is &String, which borrows a local. It does not satisfy 'static.
| Type | Satisfies `T: 'static`? |
|---|---|
| `i32`, `String`, `Vec<u8>` | Yes, they own their data |
| `&'static str` | Yes |
| `&'a str` with a shorter `'a` | No |
| `Vec<&'a str>` with a shorter `'a` | No |
Combining bounds
Lifetime bounds sit next to trait bounds and are joined with +:
fn describe<'a, T>(value: &'a T) -> &'a str
where
T: AsRef<str> + 'a,
{
value.as_ref()
}You may also bound one lifetime by another, as in 'b: 'a, which means 'b outlives 'a. The compiler can usually infer these relations. Add one yourself only when the error message asks for it.
When to write a bound yourself
- Write
T: 'staticwhen an API requires it, such as spawning threads or storing a value with no lifetime tracking. - Write
T: 'awhenTis connected to'ain a way the compiler cannot see from the signature. Boxed trait objects are the typical case, and the next chapter covers them. - Leave it out when
&'a Talready appears in a field or argument. The compiler infers it.
Exercise
A function is declared as fn store<T: 'static>(t: T). Which of these can you pass: String::from("a"), &String::from("a") bound to a local variable s as &s, or the literal "a"? Explain each.
Show answer
String::from("a") works because the String owns its data and holds no borrows. "a" works because a literal has type &'static str. &s fails because it is a reference to a local variable, and that borrow is shorter than 'static.