Sub topic 6
Relating several references with multiple lifetime parameters
This chapter assumes you know how to write a function with a single lifetime parameter like longest<'a>, and that you understand the borrowing rules for &T and &mut T. It covers when one lifetime is not enough and how to choose between one shared lifetime and several separate ones.
The problem with one shared lifetime
In longest, both inputs and the output share the single lifetime 'a. The compiler reads this as "the result is valid only as long as both inputs are". It picks 'a as the overlap of the two input lifetimes.
That is the right contract when the result may come from either input. It is too strict when the result comes from only one of them.
Declaring separate lifetimes
You can list several lifetime parameters in the angle brackets, separated by commas. Each one names a different region of the program.
fn first_of<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x
}The signature says the result borrows from x only. Nothing ties the result to _y. The caller is free to drop _y while still using the result.
fn first_of<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x
}
fn main() {
let a = String::from("kept alive");
let result;
{
let b = String::from("short lived");
result = first_of(a.as_str(), b.as_str());
} // b is dropped here
println!("{result}");
}This compiles. With one shared 'a, the same main would fail with E0597, because the result would be tied to b, which is dropped before println!.
What the signature promises
The signature is a contract, and the compiler checks the function body against it. If you declare separate lifetimes but return the wrong input, the body fails to compile.
fn broken<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
if x.len() > y.len() { x } else { y }
}This produces an error saying that lifetime 'b must outlive 'a. The function may return y, but the signature promised the result lives for 'a, and 'b is not known to last that long.
Relating lifetimes with bounds
Sometimes the result can come from either input, but the inputs have a known relationship. You can write 'b: 'a, read "'b outlives 'a". Then returning y where 'a is expected is allowed, because 'b lasts at least as long as 'a.
fn pick<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let a = String::from("abc");
let b = String::from("abcdef");
println!("{}", pick(&a, &b));
}In practice this is rare. A single shared lifetime does the same job here, since the compiler shortens a longer-lived reference to fit. Use 'b: 'a only when the relationship is part of the contract you want to state.
Choosing between one lifetime and several
| Situation | Signature shape |
|---|---|
| Result may come from either input | One shared `'a` |
| Result comes from one input only | A separate lifetime per input |
| An input is used only inside the function | No name needed, elision handles it |
Start with the simplest signature that compiles. Add separate lifetimes when a caller needs the result to outlive one of the inputs.
Exercise
Why does first_of<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str allow _y to be dropped while the result is still in use, but a version with one shared 'a does not?
Show answer
With separate lifetimes, the signature ties the result only to x, so _y's lifetime 'b is unrelated to the result. With a shared 'a, the compiler must make 'a valid for both inputs and the result, so the result cannot outlive _y, and using it after _y is dropped gives E0597.
Exercise
A function takes x: &'a str and y: &'b str and returns &'a str. The body sometimes returns y. What are two ways to fix it?
Show answer
Add the bound 'b: 'a so that y is known to live at least as long as 'a. Or give both parameters and the return type the same lifetime 'a.