Sub topic 8
Lifetime Annotations on Functions
What this chapter assumes
You should already know how shared references (&T) and mutable references (&mut T) work. You should know the rule of many readers or one writer, and why returning a reference to a local variable is rejected. This chapter shows how to write lifetime annotations in function signatures, and what they do and don't tell the compiler.
Why the compiler asks for annotations
Every reference has a lifetime. This is the region of code where the reference is valid. Most of the time the compiler works out lifetimes on its own. It asks for help when a function returns a reference and more than one input reference could be the source.
Here is the function this chapter builds on. It returns the longer of two string slices:
fn longest(x: &str, y: &str) -> &str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let a = String::from("apple");
let b = String::from("fig");
println!("{}", longest(&a, &b));
}This does not compile. The compiler reports error E0106, "missing lifetime specifier". The body returns either x or y, depending on run-time data. The compiler checks each function using only its signature and body. It checks each caller using only the signature. So the signature has to say how the output reference relates to the inputs.
The syntax
A lifetime parameter starts with an apostrophe and usually has a short lowercase name, such as 'a. You declare it in angle brackets after the function name, like a generic type. Then you attach it to references:
&'a stris a shared reference to astrthat is valid for at least'a.&'a mut Tis the mutable equivalent.'ahas no meaning until it appears in the signature and connects two or more references.
Here is the corrected function:
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("apple");
let b = String::from("fig");
println!("{}", longest(&a, &b));
}Read the signature as a contract: "For some lifetime 'a, both inputs are valid for 'a, and the result is valid for no longer than 'a." The compiler picks 'a at each call site. It chooses the overlap of the two inputs' lifetimes, which is the shorter one.
A lifetime annotation never extends how long a value lives. The value lives until its owner goes out of scope, whatever you write. Annotations only describe relationships so the compiler can check that callers respect them.
Seeing the constraint at work
The shared 'a has a consequence you can observe. Suppose the result is used after one of the inputs 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("apple");
let result;
{
let b = String::from("fig");
result = longest(&a, &b);
}
println!("{result}");
}This does not compile. The error is E0597, "b does not live long enough". The signature tied result to both inputs, so result can only be used while both a and b are alive. At the println!, b has been dropped. The compiler cannot know that longest returned a this time, so it rejects the code. If you move the println! inside the inner block, the program compiles.
This is the central idea. The compiler reasons about the signature, not about which branch ran.
Using separate lifetimes
Sometimes the output depends on only one input. A shared 'a is then too strict, because it ties the output to a parameter it never comes from. Give each parameter its own lifetime and connect only the ones that matter:
fn announce_and_return<'a, 'b>(x: &'a str, note: &'b str) -> &'a str {
println!("note: {note}");
x
}
fn main() {
let a = String::from("apple");
let result;
{
let b = String::from("fig");
result = announce_and_return(&a, &b);
}
println!("{result}");
}This compiles and prints note: fig and then apple. The result is tied only to 'a, so dropping b early is fine. The note parameter needs 'b only for the length of the call.
The compiler enforces the contract inside the body too. If you wrote -> &'a str and returned note, you would get an error such as "lifetime may not live long enough". The compiler cannot prove 'b outlives 'a, so it refuses.
Where a returned reference can come from
A returned reference must point to something that outlives the function call. That leaves two sources:
- One of the reference parameters, or data reachable from it.
- Data with the
'staticlifetime, such as string literals.
It cannot point into a local variable, because locals are dropped when the function returns. No annotation can fix that:
fn make_label<'a>() -> &'a str {
let s = String::from("temp");
&s
}
fn main() {
println!("{}", make_label());
}This does not compile. The error is E0515, "cannot return reference to local variable s". The annotation 'a promises something the function cannot deliver. The fix is to return an owned value, so the caller becomes the owner:
fn make_label() -> String {
String::from("temp")
}
fn main() {
println!("{}", make_label());
}The same applies when a function has no reference parameters and returns a reference. Without a 'static value, nothing can supply the data.
A way to decide
The flowchart below summarizes how to write a signature that returns a reference.
Elision, briefly
You have already written functions that return references without annotations, such as first_word(s: &str) -> &str. The compiler fills in the lifetimes using fixed patterns, called elision rules. They apply when there is one input reference, or when the function is a method taking &self. The next chapters cover them in detail. For now, remember that annotations are required exactly when those patterns don't give an unambiguous answer, as with longest.
The `'static` lifetime
Common errors and fixes
| Error | Message | Usual cause | Typical fix |
|---|---|---|---|
| E0106 | missing lifetime specifier | Several input references, or none, and a returned reference | Add lifetime parameters that link the output to its source |
| E0597 | borrowed value does not live long enough | Result is used after an input it is tied to was dropped | Use the result earlier, extend the owner's scope, or loosen the signature with separate lifetimes |
| E0515 | cannot return reference to local variable | Returning a borrow of something created in the function | Return an owned value |
| none | lifetime may not live long enough | Body returns a reference whose lifetime is not tied to the output | Give the relevant parameter the output's lifetime |
Summary of rules to remember
- Lifetime parameters are declared in
<>after the function name and used as&'a T. - Annotations describe relationships and never change how long data lives.
- With a shared
'a, the result is valid only as long as the shortest-lived input. - Tie the output only to the inputs it can actually come from.
- A returned reference can't outlive its source, so a reference to a local is never valid.
Exercise
This function has the signature fn pick<'a>(x: &'a str, y: &'a str) -> &'a str and always returns x. Callers drop y early and then use the result, and the compiler rejects the code. Rewrite the signature so the caller's code compiles, and say why the original was too strict.
Show answer
Use fn pick<'a, 'b>(x: &'a str, y: &'b str) -> &'a str. The original used one shared 'a, so the result was tied to both inputs and could only be used while y was alive. The new signature ties the result to x alone, which matches the body.
Exercise
What is wrong with fn greeting<'a>() -> &'a str { let s = String::from("hi"); &s }, and how do you fix it without using 'static?
Show answer
It returns a reference to the local s, which is dropped when the function returns (error E0515). No lifetime annotation can change that. Return an owned value instead: fn greeting() -> String { String::from("hi") }.