Sub topic 8
Lifetime annotations on functions
This chapter assumes you know ownership and moves, shared (&T) and mutable (&mut T) references, the rule of many readers or one writer, and why a dangling reference is rejected. You should be able to build and run a program with cargo.
Why the compiler asks for annotations
A reference is valid only while the value it points to is alive. The compiler checks this by giving every reference a lifetime, which is the span of code where the reference may be used. Most of the time it infers lifetimes on its own. When a function returns a reference, though, the compiler must know which input the result borrows from.
Here is a function that returns a reference, but the compiler can't tell which input it comes from:
fn longest(x: &str, y: &str) -> &str {
if x.len() >= y.len() { x } else { y }
}This does not compile. The compiler reports a missing lifetime specifier (E0106). The result could borrow from x or from y, and which one depends on run-time data. The signature has to say what the caller can rely on.
Writing the annotation
A lifetime parameter starts with an apostrophe and is declared in angle brackets after the function name. Here it is applied to longest:
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: "for some lifetime 'a, both inputs live at least as long as 'a, and the result is valid for 'a." In practice 'a becomes the overlap of the two input lifetimes. The result lives no longer than the shorter-lived input.
Annotations do not change how long any value lives. They describe relationships so the compiler can check the function body and every call site.
What the check catches
The annotation lets the compiler reject callers that use the result after one input 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. result may borrow from b, and b is dropped at the closing brace, so using result afterwards would create a dangling reference. The error is E0597, "b does not live long enough." Moving the println! inside the inner block fixes it.
Using different lifetimes
Sometimes the result depends on only one input. Then give each input its own lifetime and tie the result to the one it comes from:
fn first<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x
}
fn main() {
let a = String::from("apple");
let r;
{
let b = String::from("fig");
r = first(&a, &b);
}
println!("{r}");
}This compiles. The result is tied only to a, so dropping b early is fine. Tying the result to a single input gives callers more freedom, so use the narrowest relationship that is true.
Common errors
- Returning a reference to a local. No annotation can fix this. The value is dropped when the function ends, so return an owned value such as
Stringinstead. - Over-tying lifetimes. Using one
'aeverywhere compiles but can force callers to keep values alive longer than needed. - Annotating to silence the compiler. If the body returns a reference that doesn't match the signature, the compiler reports an error inside the function. Fix the body or the signature, not by adding more
'a.
Exercise
In fn pick<'a, 'b>(x: &'a str, y: &'b str) -> &'a str, can the returned reference be used after the value behind y is dropped? Why?
Show answer
Yes. The return type is tied only to 'a, which belongs to x. The signature promises nothing about y in the result, so the caller may drop y's value while still using the result, as long as x's value is alive. The function body must return x or something borrowed from it.