Sub topic 11
Lifetime bounds on generic types
A generic type T can be anything, including a reference with a short lifetime. A lifetime bound tells the compiler how long the data inside T must stay valid. This chapter covers the bound forms T: 'a and 'b: 'a, when you must write them, and what T: 'static does and doesn't mean.
This chapter assumes you can read lifetime annotations on functions, structs, and impl blocks. It also assumes you know trait bounds such as T: Debug, and how Box<dyn Trait> works.
What a lifetime bound says
A bound written T: 'a is read "T outlives 'a". It means every reference stored inside T stays valid for at least 'a.
- If
Tis&'x str, thenT: 'aholds when'xlasts at least as long as'a. - If
TisStringorVec<i32>, it holds for every'a, because those types contain no references. - If
TisWrapper<&'x u8>, the compiler checks the shortest lifetime found anywhere inside the type.
The bound is a promise about the data inside T. It does not change how long any value lives. It lets the compiler reject a call where T contains a reference that could dangle.
Bounds you rarely write: structs and references
Before Rust 2018 you had to write T: 'a on every struct that held &'a T. The compiler now infers it. This struct compiles as written:
use std::fmt::Debug;
struct Ref<'a, T> {
value: &'a T,
}
fn show<T: Debug>(r: Ref<'_, T>) {
println!("{:?}", r.value);
}
fn main() {
let n = 42;
show(Ref { value: &n });
}The type &'a T is only well-formed when T: 'a, so the compiler adds that requirement for you. The same applies to function arguments. A parameter of type &'a T lets the body assume T: 'a.
You will see older code that spells it out, as in struct Ref<'a, T: 'a>. That form is valid but redundant.
Bounds you must write: when T is not behind a reference
The compiler can only infer a bound from a visible reference type. If T is passed by value and you hand it to something with a lifetime, you must state the relationship. The usual case is turning T into a trait object:
use std::fmt::Debug;
fn boxed<'a, T: Debug + 'a>(value: T) -> Box<dyn Debug + 'a> {
Box::new(value)
}
fn main() {
let text = String::from("hello");
let b = boxed(&text);
println!("{:?}", b);
}The return type promises that the boxed value is valid for 'a. That promise is only true if everything inside T lasts that long. Without + 'a on T, the compiler stops with an error:
// fn boxed<'a, T: Debug>(value: T) -> Box<dyn Debug + 'a> {
// Box::new(value)
// }
// error[E0309]: the parameter type `T` may not live long enoughIn this call, T is &String, and the borrow of text lasts as long as b is used. The bound is satisfied. If text were dropped while b was still alive, the compiler would reject the program.
Outlives bounds between lifetimes
You can also relate two lifetime parameters with 'b: 'a, read "'b outlives 'a". Use it when a function must treat a longer-lived reference as a shorter-lived one:
fn pick<'a, 'b: 'a>(x: &'a str, y: &'b str, first: bool) -> &'a str {
if first { x } else { y }
}
fn main() {
let outer = String::from("outer");
{
let inner = String::from("inner");
println!("{}", pick(&inner, &outer, false));
}
}The function returns y where &'a str is expected. That is only safe when 'b lasts at least as long as 'a, so the bound is required. Without it the compiler reports "lifetime may not live long enough".
Writing 'b: 'a states a requirement on the caller, not a fact the function enforces. Callers that cannot satisfy it get an error at the call site.
The `'_` lifetime in generic code
'_ is the anonymous lifetime. It means "a lifetime I don't need to name, and the compiler should infer it". It has three common uses:
use std::fmt::Debug;
struct Parser<'a> {
input: &'a str,
}
impl Parser<'_> {
fn len(&self) -> usize {
self.input.len()
}
}
fn describe(p: &Parser<'_>) -> Box<dyn Debug + '_> {
Box::new(p.input)
}
fn main() {
let p = Parser { input: "abc" };
println!("{} {:?}", p.len(), describe(&p));
}impl Parser<'_>is shorthand forimpl<'a> Parser<'a>when the body never mentions'a.&Parser<'_>hides the lifetime parameter of a struct in a signature, so the reader still sees that the type borrows something.Box<dyn Debug + '_>applies the elision rules to the trait object bound. Here it ties the box to the borrow ofp.
`T: 'static` is a bound, not a location
T: 'static means "T contains no references that are shorter than the whole program". It does not mean the value lives forever. The value can be created and dropped at any time. The bound only restricts which references it may hold.
| Type | Satisfies `T: 'static`? | Reason |
|---|---|---|
| `String` | Yes | Owns its data, holds no references |
| `Vec<i32>` | Yes | Owns its data |
| `&'static str` | Yes | The reference is valid for the whole program |
| `&'a str` for a local `'a` | No | The reference can dangle |
| `Wrapper<&'a u8>` | No | Contains a short-lived reference |
The most common place you meet it is std::thread::spawn, which requires F: 'static because the new thread may outlive the function that started it:
use std::fmt::Debug;
use std::thread;
fn run<T: Debug + Send + 'static>(value: T) {
thread::spawn(move || println!("{value:?}")).join().unwrap();
}
fn main() {
run(String::from("owned"));
run("literal");
let local = String::from("borrowed");
// run(&local); // error: `local` does not live long enough
println!("{local}");
}When you need to borrow across threads, use std::thread::scope. Scoped threads are guaranteed to finish before the scope ends, so they don't need 'static.
Reading the errors
Bound errors have a recognizable shape. The message names a type parameter and says it "may not live long enough".
- E0309 says a type parameter needs a bound with a named lifetime. Add
T: 'a, using the lifetime from the signature. - E0310 says a type parameter needs
'static. Either addT: 'static, or check whether the API really needs it. Often the better fix is to give the destination a shorter lifetime, such asBox<dyn Trait + 'a>in place ofBox<dyn Trait>. - "lifetime may not live long enough" is the lifetime-to-lifetime version. Add
'b: 'awhen'breally does outlive'aat every call site. If it doesn't, change the function so it returns the shorter reference.
A quick way to choose a fix:
- Start with the narrowest bound that makes the code compile, usually
T: 'a. - Move to
'staticonly for data that must not depend on any borrow. - If you cannot name a sensible lifetime, consider owning the data instead, for example by returning
Stringrather than&str.
Summary
T: 'ameans every reference insideTlasts at least'a.'b: 'ameans'blasts at least as long as'a.- Struct definitions and
&'a Tparameters getT: 'ainferred. By-value generics that flow into trait objects need it written out. '_is a placeholder for a lifetime you don't need to name.T: 'staticallows owned types and'staticreferences, and rejects short-lived borrows.
Exercise
The function below fails with "the parameter type T may not live long enough". Rewrite its signature so that it compiles, and say which error code you expect before the fix.
fn wrap<'a, T: std::fmt::Display>(value: T) -> Box<dyn std::fmt::Display + 'a> {
Box::new(value)
}
Show answer
Add the bound T: 'a, giving fn wrap<'a, T: std::fmt::Display + 'a>(value: T) -> Box<dyn std::fmt::Display + 'a>. The error before the fix is E0309, because the missing bound uses a named lifetime and not 'static. The bound is needed because the returned box promises its contents are valid for 'a, and T could otherwise hold a shorter-lived reference.
Exercise
Which of these values can be passed to fn run<T: Send + 'static>(t: T)? (a) String::from("x"), (b) &local_string where local_string is a local variable, (c) "text", (d) vec![1, 2, 3]. Explain your choices.
Show answer
(a), (c), and (d) can be passed. String and Vec<i32> own their data and hold no references, and "text" is a &'static str. (b) is rejected because &local_string is a reference with a lifetime limited to the local variable's scope, so it does not satisfy 'static.