Sub topic 12
Lifetime annotations on functions
This chapter assumes you know how shared and mutable references work, how the borrowing rules apply to them, and why a reference cannot outlive the value it points to. The previous chapter showed that the compiler rejects dangling references. Here you learn how to describe, in a function signature, how the lifetimes of its inputs and outputs relate.
What a lifetime annotation says
A lifetime is the region of code in which a reference is valid. Every reference has one, and most are inferred. The compiler cannot always infer how the lifetime of a returned reference relates to the lifetimes of the arguments, so it asks you to state the relationship.
An annotation does not change how long any value lives. It describes a relationship that the compiler then checks against the code in the function body and at every call site.
Lifetime names start with an apostrophe and are usually short: 'a, 'b. You declare them in angle brackets after the function name, then attach them to reference types:
&i32is a reference with an inferred lifetime.&'a i32is a reference with the lifetime'a.&'a mut i32is a mutable reference with the lifetime'a.
Why the compiler needs help
Consider a function that returns the longer of two string slices:
// Does not compile:
// fn longest(x: &str, y: &str) -> &str {
// if x.len() >= y.len() { x } else { y }
// }The compiler reports error[E0106]: missing lifetime specifier. The return value is a borrow, but the signature does not say whether it borrows from x or from y. The body returns one or the other depending on runtime data, so the compiler cannot work it out. The caller needs to know which argument must stay alive while the result is in use.
The annotated version
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 reads: for some lifetime 'a, both parameters are valid for at least 'a, and the result is valid for 'a. When a caller passes references with different real lifetimes, the compiler picks 'a as the overlap of the two, which is the shorter one. The result is therefore only guaranteed valid for that shorter region.
How the compiler checks a call
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 is long");
let result;
{
let b = String::from("xyz");
result = longest(a.as_str(), b.as_str());
println!("{result}");
}
// println!("{result}");
}This program compiles because result is used only while b is alive. If you uncomment the last println!, the compiler rejects it with error[E0597]: b does not live long enough. The result might point into b, and b is dropped at the closing brace.
The compiler never looks at which branch of the if actually runs. It assumes the worst case allowed by the signature.
Annotations relate parameters, they do not lengthen anything
You can use different lifetime parameters when the output depends on only some of the inputs:
fn first_of<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x
}
fn main() {
let keep = String::from("kept");
let word;
{
let temp = String::from("temporary");
word = first_of(&keep, &temp);
}
println!("{word}");
}The result is tied only to x, so temp can be dropped before word is used. Giving both parameters 'a here would be accepted by the signature, but it would make callers' code more restrictive than necessary. Use the loosest annotations that are still true.
When a parameter does not affect the output, you can leave its lifetime out entirely: fn first_of<'a>(x: &'a str, _y: &str) -> &'a str.
Returning references to local data
An output lifetime must come from an input. This fails whatever annotations you write:
// Does not compile:
// fn make<'a>() -> &'a str {
// let s = String::from("temporary");
// s.as_str()
// }The error is E0515: cannot return reference to local variable. The value s is dropped when the function returns, so the reference would dangle. A lifetime parameter cannot fix this. Return an owned String instead.
Reading signatures
| Signature | Meaning |
|---|---|
| `fn f<'a>(x: &'a str) -> &'a str` | The result borrows from `x`. |
| `fn f<'a>(x: &'a str, y: &'a str) -> &'a str` | The result may borrow from either. Both must outlive its use. |
| `fn f<'a, 'b>(x: &'a str, y: &'b str) -> &'a str` | The result borrows only from `x`. |
| `fn f(x: &str) -> String` | The result is owned and has no lifetime relationship. |
| `fn f() -> &'static str` | The result is valid for the whole program, such as a string literal. |
Common mistakes
- Adding
'aeverywhere to silence an error. The annotation must match what the body does. If the body returns onlyx, tyingyto the result only makes callers fail. - Expecting an annotation to extend a value's life. It cannot. It only lets the compiler verify that callers keep values alive long enough.
- Returning a reference to a local variable. Return an owned value, or take a reference as a parameter and return a part of it.
- Forgetting that the overlap is the shortest input lifetime. A result built from two arguments is only as valid as the shorter-lived one.
Exercises
Exercise
Why does fn pick(x: &str, y: &str) -> &str fail to compile, and how do you fix it if the function returns either argument?
Show answer
There are two input references and the output is a reference, so the compiler cannot tell which input the output borrows from. Declare one lifetime and use it on both inputs and the output: fn pick<'a>(x: &'a str, y: &'a str) -> &'a str.
Exercise
In longest(a.as_str(), b.as_str()), a lives in the outer scope and b in an inner block. Where can the result be used?
Show answer
Only inside the inner block. The lifetime 'a is the overlap of both inputs, which is the shorter one, so the result cannot be used after b is dropped.