Sub topic 12
Lifetime Annotations on Functions
This chapter assumes you know how shared and mutable references work, the borrowing rules, and why Rust rejects dangling references. Here you will learn what a lifetime annotation says and when a function signature needs one.
Why the compiler needs help
A reference is valid only while the value it points to is alive. The borrow checker compares how long each reference lives with how long its target lives. Inside one function body it can see all of that. At a function boundary it cannot, because it checks each function by its signature alone.
Consider a function that returns one of two references. The compiler cannot tell which input the result comes from, so it cannot tell how long the result stays valid. It asks you to say.
Writing an annotation
A lifetime parameter starts with an apostrophe and sits in angle brackets after the function name. You attach it to references with &'a.
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("longer text");
let b = String::from("short");
println!("{}", longest(&a, &b));
}The signature says: both inputs and the output share the lifetime 'a. In practice 'a becomes the overlap of the two input lifetimes, which is the shorter one. The returned reference is valid only while both inputs are valid.
An annotation does not change how long any value lives. It only describes a relationship so the compiler can check callers.
What the check catches
The caller must keep both inputs alive for as long as it uses the result. This program fails to compile:
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("longer text");
let result;
{
let b = String::from("short");
result = longest(&a, &b);
}
println!("{result}");
}The error is ` b does not live long enough . result is tied to 'a, which is limited by b. Using result after b` is dropped would be a dangling reference, so Rust refuses.
Choosing the right annotation
Annotate only what the output truly depends on. If the result never comes from y, give y its own lifetime or none:
fn first<'a>(x: &'a str, _y: &str) -> &'a str {
x
}
fn main() {
let a = String::from("keep");
let r;
{
let b = String::from("temporary");
r = first(&a, &b);
}
println!("{r}");
}This compiles, because the result depends only on a. A looser signature is easier for callers to satisfy.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `missing lifetime specifier` | Output is a reference and the compiler cannot tell which input it borrows from | Add `<'a>` and tie the output to the right inputs |
| `does not live long enough` | An input is dropped while the result is still in use | Extend the input's scope or restructure the caller |
| `cannot return reference to local variable` | The function returns a borrow of a value created inside it | Return an owned value such as `String` |
Exercise
In fn pick<'a>(x: &'a str, y: &str) -> &'a str, which argument may the returned reference borrow from, and why does the caller not need to keep the other argument alive?
Show answer
The result may borrow only from x, because only x has lifetime 'a, the same lifetime as the return type. y has an unrelated lifetime, so the compiler knows the result never points into it and y can be dropped while the result is still in use.