Sub topic 1
Lifetimes and Outlives Bounds: A Quick Refresher
Every reference in Rust carries a lifetime. The later chapters on variance and higher-ranked trait bounds ask one question again and again: when may the compiler treat one lifetime as another? This chapter sets up the vocabulary for that question. The main term is the outlives relation, written 'long: 'short.
Prerequisites
This chapter assumes you already know:
- Ownership, borrowing, and the difference between
&Tand&mut T. - How to write a basic lifetime annotation on a function or a struct.
- Generics and trait bounds such as
T: Display. - Closures and the
Fn,FnMutandFnOncetraits. These matter more in later chapters.
If you can explain why fn longest<'a>(a: &'a str, b: &'a str) -> &'a str needs its annotation, you are ready.
What a lifetime is
A lifetime is a region of code in which a reference is guaranteed to be valid. Three facts shape everything that follows:
- Lifetimes exist only at compile time. They produce no machine code and cost nothing at runtime.
- A lifetime is not the lifetime of a value. It is the span for which a particular borrow is used and must stay valid. The borrow checker infers that span from your code.
- A lifetime name such as
'ain a signature is a placeholder. The caller's code picks the actual region, and the compiler checks that your function body works for any region the caller could pick.
Here is the classic failure the borrow checker exists to stop:
fn main() {
let r;
{
let x = 5;
r = &x;
} // `x` is dropped here
println!("{r}"); // error[E0597]: `x` does not live long enough
}The borrow &x would have to last as long as r is used. That is past the end of the inner block, where x no longer exists. The compiler rejects the program.
Lifetime parameters in signatures
A signature with lifetime parameters describes how the lifetimes of the inputs relate to the lifetime of the output. Compare two versions of one function:
fn first<'a, 'b>(a: &'a str, _b: &'b str) -> &'a str {
a
}
fn main() {
let keep = String::from("kept");
let result;
{
let temp = String::from("temporary");
result = first(&keep, &temp);
} // `temp` is dropped, but `result` only borrows from `keep`
println!("{result}");
}first says that the result borrows only from a. The two parameters use separate names, so temp can die while result stays in use. If you wrote longest<'a>(a: &'a str, b: &'a str) -> &'a str instead, both inputs would share one name. The result would then be tied to whichever input has the shorter region, and this main would no longer compile.
So the annotation does not lengthen or shorten any borrow. It tells the compiler which borrows are linked, so the compiler can check every caller.
The outlives relation
Sometimes two lifetimes are not equal, but one is known to cover the other. We write that as 'long: 'short and read it as "'long outlives 'short". It means the region 'long contains the whole region 'short.
'a: 'aalways holds, so every lifetime outlives itself.'static: 'aholds for every'a, because'staticis the entire program.- The relation is transitive. If
'a: 'band'b: 'c, then'a: 'c.
Here is the same idea as a diagram. Read each arrow as "outlives".
You can state the relation in a signature. This function accepts one borrow that is known to be at least as long as the other:
fn pick<'long: 'short, 'short>(a: &'long str, b: &'short str) -> &'short str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let outer = String::from("lives longer");
{
let inner = String::from("short");
println!("{}", pick(&outer, &inner));
}
}The body returns a where &'short str is expected. That is allowed because 'long: 'short, so a &'long str can be used wherever a &'short str is wanted. The next chapter explains this substitution and names it lifetime subtyping.
You can also write the bound in a where clause, which reads better when a signature has many parameters:
fn pick_where<'a, 'b>(a: &'a str, b: &'b str) -> &'b str
where
'a: 'b,
{
if a.len() >= b.len() { a } else { b }
}
fn main() {
println!("{}", pick_where("abc", "de"));
}Outlives bounds on types
The same notation applies to types. T: 'a means that every reference stored inside T is valid for at least 'a. In other words, T does not contain a borrow that ends before 'a does.
Two common forms:
| Bound | Meaning | Types that satisfy it |
|---|---|---|
| `T: 'a` | `T` holds no reference shorter than `'a` | `String`, `i32`, `&'a str`, `&'static str` |
| `T: 'static` | `T` holds no reference except `'static` ones | `String`, `Vec<u8>`, `&'static str`; not `&'a str` for a local `'a` |
The second row is a frequent source of confusion. T: 'static does not mean the value lives for the whole program. It means the type contains no short borrows, so it could be kept as long as you like. An owned String satisfies 'static, and you can drop it whenever you want.
fn needs_static<T: 'static>(_value: T) {}
fn main() {
needs_static(String::from("owned"));
needs_static(42u8);
needs_static("a literal");
let local = String::from("local");
// needs_static(&local); // error: borrowed value does not live long enough
println!("{local}");
}Bounds like this show up when a value is stored behind a trait object or sent to another thread. Here is a case where the bound is needed on a function:
use std::fmt::Debug;
fn erase<'a, T>(value: T) -> Box<dyn Debug + 'a>
where
T: Debug + 'a,
{
Box::new(value)
}
fn main() {
let text = String::from("hello");
let boxed = erase(&text);
println!("{boxed:?}");
}The returned Box<dyn Debug + 'a> may hide a type that contains borrows. The bound T: 'a guarantees that none of those borrows ends before 'a. Without it, the compiler reports that the parameter type T may not live long enough.
Implied bounds on structs
You rarely need to write T: 'a on a struct. Since Rust 2018, the compiler infers it from the fields:
struct Holder<'a, T> {
inner: &'a T, // the compiler infers `T: 'a`
}
fn main() {
let n = 7;
let h = Holder { inner: &n };
println!("{}", h.inner);
}A reference &'a T is only well formed if T: 'a. Without that rule, inner could point at data that has already been freed. Older code wrote struct Holder<'a, T: 'a>, which still compiles but is now redundant.
Common mistakes
- Reading
'staticas "never dropped". It describes a bound on what a type may borrow, not how long a particular value exists. - Adding
'staticto silence an error. That often forces callers to pass only owned or literal data. Look for the missing'alink between input and output first. - Using one lifetime name for every parameter. This ties unrelated borrows together, as the
longestandfirstcomparison showed. - Assuming an annotation changes how long data lives. It only describes relationships that the compiler then checks.
Where this leads
The pick function relied on one unstated rule: a longer borrow may be used where a shorter one is expected. The next chapter states that rule precisely as lifetime subtyping. After that, the variance chapters explain which types allow the substitution and which forbid it, and the higher-ranked chapters explain what it means to accept a reference of any lifetime.
Exercise
In fn f<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str, which of the two parameters may the function return, and why? Would T: 'static hold for String, and would it hold for &'a str where 'a is a local lifetime?
Show answer
The function may return either one. x already has type &'a str. y has type &'b str, and since 'b: 'a ('b outlives 'a), a &'b str can be used where a &'a str is expected. String: 'static holds, because a String contains no references at all. &'a str: 'static does not hold when 'a is a local lifetime, because the type contains a borrow shorter than 'static.