Sub topic 5
Lifetimes in function signatures
This chapter assumes you know basic Rust syntax, ownership and moves, the rules for &T and &mut T, and the difference between String and &str. It also assumes you have seen the 'a annotation syntax. Here you will apply it to functions that return references.
Why a signature needs lifetimes
The compiler checks each function on its own. It does not read the body of a function when it checks a call to it. It uses only the signature. If a function takes two references and returns one, the signature must say which input the result may borrow from.
This function 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 result could come from x or from y, depending on a runtime check. The compiler cannot know which, so you must describe the relationship.
Adding the annotation
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");
let b = String::from("short");
let result = longest(a.as_str(), b.as_str());
println!("{result}");
}Read the signature as follows:
<'a>declares a lifetime parameter, in the same way<T>declares a type parameter.x: &'a strandy: &'a strsay both inputs must be valid for at least'a.-> &'a strsays the result is valid for'a.
The annotation does not change how long any value lives. It describes a relationship that the compiler then checks at each call site. At the call, the compiler picks 'a as the region where both a and b are alive. The result may be used only inside that region.
What the compiler enforces at the call
A caller that lets one input die while the result is still in use is rejected:
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");
let result;
{
let b = String::from("short");
result = longest(a.as_str(), b.as_str());
} // b is dropped here
println!("{result}"); // error[E0597]: `b` does not live long enough
}Even if a is the longer string at runtime, the signature only promises "valid while both are". The compiler checks against that promise, not against the actual data.
Tie the result only to what it uses
If the result never comes from an input, do not tie it to that input. Separate lifetime parameters express this:
fn first_of<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x
}
fn main() {
let a = String::from("kept");
let result;
{
let b = String::from("dropped soon");
result = first_of(a.as_str(), b.as_str());
}
println!("{result}");
}This compiles. The signature says the result depends only on x, so y may be dropped first. Use one shared lifetime when the result may come from either input. Use separate lifetimes when it comes from only one.
Common errors
| Error | Cause | Usual fix |
|---|---|---|
| E0106 missing lifetime specifier | Several input references, and the compiler cannot tell which one the output borrows from | Add lifetime parameters that name the source |
| E0597 does not live long enough | A caller drops an input while the result is still used | Move the use inside the scope, or restructure ownership |
| Returning a reference to a local | The output has no input to borrow from | Return an owned value such as `String` |
The last row deserves a note. This function can never be fixed with an annotation:
fn make() -> &'static str {
let s = String::from("hi");
&s // error[E0515]: cannot return reference to local variable `s`
}The data is dropped when the function returns. Return String instead.
Exercise
A function fn pick<'a>(x: &'a str, y: &'a str, flag: bool) -> &'a str returns x if flag is true and y otherwise. A caller passes a long-lived x and a short-lived y, then uses the result after y is dropped. Does it compile, even if flag is always true at runtime? Why?
Show answer
No. The signature ties the result to both inputs through the single lifetime 'a, so the compiler treats the result as valid only while both are alive. It checks the signature, not the runtime value of flag, so it reports E0597 for y.
Exercise
Rewrite fn first_of(x: &str, _y: &str) -> &str { x } so that it compiles and the result does not depend on _y.
Show answer
fn firstof<'a, 'b>(x: &'a str, y: &'b str) -> &'a str { x } (writing _y: &str with only 'a on x also works).