Sub topic 4
Reading and Writing Lifetime Annotations
This chapter assumes you know basic Rust syntax, ownership and moves, the rules for &T and &mut T, and the difference between String and &str. You have already seen why the compiler rejects dangling references. Here you learn the syntax that lets you describe reference relationships to the compiler.
What an annotation is
A lifetime annotation is a name that starts with an apostrophe, such as 'a. It labels a region of code during which a reference is valid. Lifetime names are declared in angle brackets, like generic type parameters, and used after the &.
| Written form | Meaning |
|---|---|
| `&i32` | A shared reference, lifetime inferred or elided |
| `&'a i32` | A shared reference with lifetime `'a` |
| `&'a mut i32` | A mutable reference with lifetime `'a` |
| `<'a>` | Declares a lifetime parameter named `'a` |
Convention is short lowercase names: 'a, 'b, and so on. A descriptive name such as 'input is also legal.
What annotations do not do
An annotation never changes how long a value lives. It does not extend a lifetime or keep data alive. It only describes a relationship between the references in a signature, so the compiler can check that relationship at each call site.
Think of it as a contract. The function promises something about its output. The caller must keep the inputs alive long enough to honor it.
Writing your first annotation
This function returns one of two references. Without annotations, the compiler cannot tell which input the result borrows from, and it reports error E0106 (missing lifetime specifier).
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let a = String::from("long string");
let b = String::from("short");
let result = longest(a.as_str(), b.as_str());
println!("{result}");
}Read the signature in three parts:
longest<'a>declares a lifetime parameter named'a.x: &'a strandy: &'a strsay both inputs are valid for at least'a.-> &'a strsays the result is valid for no longer than'a.
When the caller passes in two references with different real lifetimes, the compiler picks 'a as the overlap of the two, which is the shorter one. The result may be used only inside that overlap.
Checking the contract at the call site
Here the caller breaks the contract. The result is used after b is gone.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let a = String::from("long string");
let result;
{
let b = String::from("short");
result = longest(a.as_str(), b.as_str());
} // b is dropped here
println!("{result}");
}
// error[E0597]: `b` does not live long enoughEven though longest returns a at runtime, the signature only promises that the result is tied to both inputs. The compiler checks signatures, not function bodies, when it checks callers.
Reading a signature as a contract
When you meet an unfamiliar signature, ask two questions:
- Which input lifetimes does the output share a name with?
- Is any input left with a different or unnamed lifetime, which means the output does not depend on it?
A signature with a single name, as in longest, ties the output to every input. Later chapters show how separate names loosen this.
Common mistakes
- Adding
'aeverywhere "to make it compile". Annotations must reflect how the data really flows. - Declaring
'aand then using it on only one parameter. That is legal but usually means the name is unnecessary. - Expecting an annotation to fix a dangling reference. If the data really dies too early, the fix is to change ownership, for example by returning a
String.
Exercise
In fn pick<'a>(x: &'a str, y: &'a str) -> &'a str, x lives for the whole program and y lives only in an inner block. Where can the result be used?
Show answer
Only while y is still alive, which is inside the inner block. The compiler sets 'a to the overlap of the two input lifetimes, which is the shorter one, and the result is limited to it.
Exercise
Does writing &'a str instead of &str make the referenced string live longer?
Show answer
No. An annotation only describes a relationship for the compiler to check. It never changes how long the data lives.