Sub topic 4
Reading and writing lifetime annotations
This chapter assumes you know basic Rust syntax, ownership and moves, the borrowing rules for &T and &mut T, and the difference between String and &str. The previous chapters showed why the compiler rejects dangling references. Here you learn the notation Rust uses to describe how long references are valid, so you can read it in signatures and write it yourself.
What a lifetime annotation is
A lifetime annotation is a name for a region of code during which a reference is valid. It starts with an apostrophe, followed by a short identifier: 'a, 'b, 'input.
An annotation does not create a lifetime and cannot make data live longer. Every reference already has a lifetime, and the compiler works it out from how the reference is used. An annotation only states a relationship between the lifetimes of several references. The compiler then checks that the function body and every caller respect that relationship.
Think of an annotation as a promise written in the signature:
- Inside the function, the compiler checks that the body keeps the promise.
- At each call site, the compiler assumes the promise and uses it to decide how long the inputs must stay borrowed.
The syntax
A lifetime parameter is declared in angle brackets, in the same list as generic type parameters. You then use it after the & in a reference type.
fn pick<'a>(x: &'a str, _other: &str) -> &'a str {
x
}
fn main() {
let first = String::from("alpha");
let second = String::from("beta");
let chosen = pick(&first, &second);
println!("{chosen}");
}Read the signature from left to right:
<'a>declares a lifetime parameter named'a.x: &'a strsaysxis a reference that is valid for at least'a._other: &strhas no name. The compiler gives it a fresh lifetime that is not related to anything else.-> &'a strsays the returned reference is valid for'a.
Reading the whole signature, the result is tied to x and has nothing to do with _other. A caller may keep using chosen after second is gone, as long as first is alive.
Forms you will see
| Written form | Meaning |
|---|---|
| `&'a T` | Shared reference to `T`, valid for `'a` |
| `&'a mut T` | Mutable reference to `T`, valid for `'a` |
| `&T` | Shared reference with an elided (inferred) lifetime |
| `&'static T` | Reference valid for the whole program run |
| `Holder<'a>` | A type that contains a reference valid for `'a` |
| `Holder<'_>` | The same, with the lifetime left for the compiler to infer |
| `T: 'a` | Every reference inside `T` must be valid for at least `'a` |
The mut keyword comes after the lifetime: &'a mut i32, not &mut 'a i32.
fn bump<'a>(counter: &'a mut i32) -> &'a mut i32 {
*counter += 1;
counter
}
fn main() {
let mut n = 0;
let r = bump(&mut n);
*r += 10;
println!("{n}");
}This prints 11. The returned reference keeps n mutably borrowed for as long as r is used. The last use of r is *r += 10, so n can be read again on the next line.
Reading a signature as a graph of relationships
When you meet an unfamiliar signature, ignore the types at first and look only at which references share a lifetime name. References that share a name are related. References with different names or no name are independent.
The solid arrow means the result borrows from x. The dotted line means _other plays no part in how long the result is valid.
Where lifetime parameters can be declared
Lifetime parameters are declared in more than one place, and each place decides how far the name is visible.
- Functions and methods:
fn name<'a>(...). The name is visible in that signature and body. - Structs and enums:
struct Holder<'a> { ... }. The name is visible in the fields. implblocks:impl<'a> Holder<'a> { ... }. The name is visible in the whole block. You must declare it afterimplbefore you can use it inHolder<'a>.- Traits and type aliases:
trait Parser<'a>andtype Pair<'a> = (&'a str, &'a str);.
Lifetime parameters go before type parameters in the list: fn f<'a, T>(x: &'a T).
Later chapters cover structs, impl blocks and bounds in detail. For now, notice that the notation is the same everywhere: declare a name once, then use it where a reference or a lifetime-carrying type appears.
Types that carry lifetimes
A type with a lifetime parameter holds a reference somewhere inside it. When you use that type, you should show the lifetime, even if you let the compiler fill in the name.
struct Holder<'a> {
text: &'a str,
}
fn wrap(s: &str) -> Holder<'_> {
Holder { text: s }
}
fn main() {
let owned = String::from("abc");
let h = wrap(&owned);
println!("{}", h.text);
}The '_ is the anonymous lifetime. It means "a lifetime goes here, and the compiler should infer it". Writing Holder<'_> tells the reader that Holder borrows something, which -> Holder would hide. Since Rust 2018, a lint (elided_lifetimes_in_paths, off by default) can ask you to write it. Many teams treat '_ as good style.
Here the compiler infers that the output lifetime equals the single input lifetime. The next chapters explain that rule in full.
What annotations do not do
Three misunderstandings cause most early confusion.
- Annotations do not extend a lifetime. Writing
'aon a reference never keeps the data alive longer. If the data is dropped too early, you get an error, not a longer life. - Annotations do not appear in the compiled program. Lifetimes are erased after checking. They cost nothing at run time.
- The name
'ahas no meaning by itself.'ais not "the lifetime of x". Within one signature, it is a label the compiler uses to say "these references must be valid together".
A caller never writes 'a. At each call, the compiler picks a concrete region for 'a: the overlap of every input that carries that name.
The body must keep the promise
The compiler checks the body against the signature. If you promise more than the body can deliver, the program is rejected.
fn bad<'a>(x: &'a str, y: &str) -> &'a str {
y
}
// error: lifetime may not live long enough
// `y` has an anonymous lifetime, but it needs to outlive `'a`The signature says the result is valid for 'a. The body returns y, whose lifetime is unrelated to 'a. The compiler cannot prove the promise, so it reports an error inside the function, not at the caller.
Two fixes are common. If the result really comes from y, give y the same lifetime: y: &'a str. If the result should come from x, return x.
Naming lifetimes
Short names such as 'a and 'b are the convention for small generic functions, just as T is for types. Descriptive names help when a signature has several lifetimes with different roles.
struct Parser<'input> {
source: &'input str,
position: usize,
}
impl<'input> Parser<'input> {
fn rest(&self) -> &'input str {
&self.source[self.position..]
}
}
fn main() {
let text = String::from("let x = 1;");
let p = Parser { source: &text, position: 4 };
println!("{}", p.rest());
}This prints x = 1;. The name 'input tells the reader what the lifetime is about. Because rest returns &'input str, the result stays valid even after the Parser itself is dropped. The result is tied to the text, not to the parser. Had the signature returned an elided &str, the result would be tied to &self instead.
Two names are reserved. 'static means the whole program run, and '_ is the anonymous lifetime. You cannot declare your own parameter with either name.
Common reading and writing errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `E0106: missing lifetime specifier` | A returned reference has several possible sources and elision cannot choose | Add a named lifetime that links the output to the right input |
| `E0261: use of undeclared lifetime name` | You used `'a` without declaring it in `<...>` | Add `<'a>` to the function, or to the `impl` and the type |
| "lifetime may not live long enough" | The body returns a reference whose lifetime is not tied to the promised one | Relate the lifetimes in the signature or return a different value |
| Everything has `'a` and the code still fails | One name forces all inputs to be valid together, which is more than needed | Use a separate name for the independent input |
Summary
- A lifetime name such as
'ais declared in angle brackets and used after&. - Annotations describe relationships between references. They do not change how long data lives.
- Shared names mean "valid together". Different names or no name mean "independent".
'_asks the compiler to infer a lifetime and shows readers that a type borrows.- The function body is checked against the signature, so a promise the body cannot keep is an error.
Exercise
In fn f<'a>(x: &'a str, y: &str) -> &'a str, which argument can the returned reference borrow from, and what happens if the body returns y?
Show answer
The result can borrow only from x, because x and the return type share 'a. Returning y is rejected with "lifetime may not live long enough". y has its own anonymous lifetime, so the compiler cannot show it is valid for 'a. To allow it, declare y: &'a str.
Exercise
What does Holder<'_> tell the compiler and the reader that plain Holder does not?
Show answer
It marks that Holder contains a borrowed reference and asks the compiler to infer the lifetime. The reader can see from the signature that the value borrows data and cannot outlive its source.