Sub topic 5
Lifetimes in function signatures
This chapter assumes you know Rust functions, generics, shared and mutable references, and the difference between String and &str. It also assumes you know why the compiler rejects dangling references, which the earlier chapters cover. Here you will learn to write lifetime annotations on functions that return references, and to read what those annotations promise.
The problem: which input does the output borrow from?
Take a function that returns the longer of two string slices.
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}This does not compile. The compiler reports error[E0106]: missing lifetime specifier and adds that the return type contains a borrowed value, but the signature does not say whether it is borrowed from x or y.
The compiler cannot work this out from the body. It checks each function using only the function's signature, and it checks each call using only the callee's signature. It never looks inside a callee while checking a caller. So the signature must state how the output relates to the inputs.
Writing the annotation
A lifetime parameter is declared in angle brackets, before any type parameters. It is then attached to each reference it describes.
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: "for some lifetime 'a, both inputs are valid for at least 'a, and the result is valid for 'a."
Three points about this:
- The annotation does not change how long any value lives. It describes relationships that already exist, so the compiler can check them.
'ais a name for a region of the program, and the compiler picks the region at each call site.- The names have no meaning of their own.
'a,'xand'inputall work, and short names are conventional.
What the caller sees
When you call longest, the compiler picks an 'a that every argument can satisfy. Each argument must be valid for 'a, so 'a can be no longer than the shortest-lived argument. The result then counts as borrowed for 'a.
In practice the result may be used only while all of the arguments are still alive. The next program fails for that reason.
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());
}
println!("{result}");
}
// error[E0597]: `b` does not live long enoughAt runtime result happens to point at a, which is still alive. The compiler does not know that. The signature says the result may borrow from either argument, so it must assume b could be the source. Moving the println! inside the inner block fixes the program.
What the compiler checks inside the body
The signature is a contract, and the compiler checks the body against it. If the body returns a reference that the signature does not allow, the function is rejected.
fn pick<'a>(x: &'a str, y: &str) -> &'a str {
y
}
// error: lifetime may not live long enoughHere y has its own unnamed lifetime. Nothing says it lasts as long as 'a, so returning it breaks the promise made in the signature. The fix is to return x, or to give y the lifetime 'a as well. Which one is right depends on what the function means to promise.
Parameters that do not feed the result need no shared lifetime. You can leave them unannotated, as y is above. Giving every reference the same 'a is a common beginner habit. It makes the signature stricter than necessary and can cause avoidable errors at call sites. The next chapter covers separate lifetime parameters.
Returning references to local data
The most common function-level lifetime error is returning a reference to something created inside the function.
fn make_greeting<'a>(name: &'a str) -> &'a str {
let s = format!("Hello, {name}");
&s
}
// error[E0515]: cannot return reference to local variable `s`No annotation can fix this. s is dropped when the function returns, so any reference to it would dangle. You have two real options:
- Return an owned value, here
String, so the caller owns the result. - Return a reference derived from an input, which already lives longer than the call.
fn make_greeting(name: &str) -> String {
format!("Hello, {name}")
}
fn main() {
println!("{}", make_greeting("Ferris"));
}A function with no reference parameters cannot return a borrowed value tied to its arguments, because there is nothing to borrow from. The only reference it can return is one that lives for the whole program, written 'static.
fn greeting() -> &'static str {
"hello"
}
fn main() {
println!("{}", greeting());
}Do not use 'static to silence an error. If a function returns a reference to computed data, you almost always want to return an owned type.
Lifetimes next to type parameters
Lifetime parameters go first in the angle brackets, followed by type parameters. Trait bounds can sit inline or in a where clause.
use std::fmt::Display;
fn longest_with_note<'a, T>(x: &'a str, y: &'a str, note: T) -> &'a str
where
T: Display,
{
println!("Note: {note}");
if x.len() > y.len() { x } else { y }
}
fn main() {
let a = String::from("alpha");
let b = String::from("be");
println!("{}", longest_with_note(&a, &b, 42));
}note is owned (T), so it takes no part in the lifetime relationship. Only the references that appear in the output matter.
Mutable borrows in signatures
The rules are the same for &mut, but the effect is stronger. If a function takes &'a mut and returns a reference with lifetime 'a, the mutable borrow lasts as long as the returned reference is in use.
fn push_and_get<'a>(items: &'a mut Vec<String>, s: &str) -> &'a String {
items.push(s.to_string());
items.last().unwrap()
}
fn main() {
let mut items = Vec::new();
let last = push_and_get(&mut items, "first");
println!("{last}");
// Using `items` here, after the last use of `last`, is fine.
items.push("second".to_string());
println!("{}", items.len());
}While last is alive, items cannot be touched. If you used items between the call and the final use of last, you would get an error about a conflicting borrow. The returned reference is shared (&String), but it keeps the original &mut borrow alive.
Reading a signature as a contract
| Signature | What it promises |
|---|---|
| `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 input, so it is valid only while both are. |
| `fn f<'a>(x: &'a str, y: &str) -> &'a str` | The result borrows from `x` only. `y` can be dropped right after the call. |
| `fn f() -> &'static str` | The result lives for the whole program. |
| `fn f(x: &str) -> String` | The result is owned and no lifetime is involved. |
Common mistakes
- Treating annotations as instructions. They never extend a lifetime. If a value is dropped too early, the fix is to change where the value lives, or to return an owned value.
- Adding
'ato every reference. Annotate only what the output depends on. - Returning a reference to a local. Return an owned value instead.
- Expecting the compiler to look at the body of a callee. It reads only the signature, so a body that happens to return
xdoes not help callers unless the signature says so.
Exercise
The function below fails to compile with E0106. Rewrite it so that the result may be used even after prefix has been dropped, and say why the signature you chose is correct.
fn pick(text: &str, prefix: &str) -> &str {
if text.starts_with(prefix) { text } else { "" }
}
Show answer
Annotate the signature as fn pick<'a>(text: &'a str, prefix: &str) -> &'a str. The result is either text or the literal "", and a string literal is &'static str, which satisfies any 'a. Because prefix has no connection to the output, it needs no shared lifetime, so it can be dropped while the result is still in use. If you also wrote &'a str for prefix, the code would compile, but callers would be forced to keep prefix alive as long as the result.