Sub topic 1
Lifetimes and Outlives Bounds: A Quick Refresher
Prerequisites
This chapter assumes you already know the following:
- Ownership, borrowing and references in Rust.
- Basic lifetime annotations on functions and structs.
- Generics and trait bounds.
You do not need to know variance or higher-ranked bounds yet. Later chapters cover them. This chapter fixes the vocabulary they build on.
What a lifetime is
A lifetime is a name for a region of code in which a reference is valid. The borrow checker compares these regions to make sure no reference outlives the value it points to. Lifetimes exist only at compile time. They leave no trace in the compiled program.
In fn longest<'a>(a: &'a str, b: &'a str) -> &'a str, the name 'a is a parameter, like a type parameter. The caller picks a concrete region for it. The signature promises that the result is valid for as long as 'a.
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let outer = String::from("lives longer");
{
let inner = String::from("short");
let r = longest(&outer, &inner);
println!("{r}");
}
}Here &outer is valid for the whole of main, but &inner is valid only inside the inner block. One 'a has to cover both arguments. The compiler picks the shorter region, which is the inner block. The result r is only used inside that block, so the program compiles.
The outlives relation
The bound 'long: 'short is read "'long outlives 'short". It means the region 'long contains the region 'short. A reference that is valid for 'long is also valid for any shorter region.
Two points are easy to miss:
- Outlives is reflexive.
'a: 'aalways holds. 'static: 'aholds for every'a. A'staticreference is valid for the whole program.
You write outlives bounds on lifetime parameters, and you can also put them on types:
fn first_word<'long: 'short, 'short>(
long_lived: &'long str,
_short_lived: &'short str,
) -> &'short str {
long_lived.split(' ').next().unwrap_or("")
}
struct Holder<'a, T: 'a> {
value: &'a T,
}
fn main() {
let text = String::from("hello world");
let other = String::from("x");
println!("{}", first_word(&text, &other));
let h = Holder { value: &text };
println!("{}", h.value);
}The 'long: 'short bound lets the function return a 'long reference as a 'short one. The bound T: 'a means every reference stored inside T is valid for at least 'a. It is what makes &'a T well-formed. Since Rust 2018 the compiler infers T: 'a for structs, so you rarely write it by hand.
How the pieces fit together
The checker treats lifetimes as a set of constraints. Each call and each assignment adds a constraint of the form 'x: 'y. The checker then looks for regions that satisfy all of them.
If no assignment of regions satisfies every constraint, you get the familiar error "borrowed value does not live long enough". The next chapter looks at how the compiler may treat a 'long reference as a 'short one. That is lifetime subtyping.
Check your understanding
Exercise
A function has the signature fn pick<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str. Which of the two arguments is allowed to live longer, and why can y be returned?
Show answer
The bound 'b: 'a says 'b outlives 'a, so y may live longer than x. Because a 'b reference is also valid for the shorter region 'a, returning y as &'a str is allowed.