Sub topic 6
Relating Several References with Multiple Lifetime Parameters
This chapter assumes you can write Rust functions, structs, and impl blocks, and that you know the basic borrowing rules. It also assumes you have seen a signature like fn longest<'a>(x: &'a str, y: &'a str) -> &'a str. Here you will learn when one lifetime parameter says too much, how to use several, and what each choice promises to callers.
Why one shared lifetime can be too strict
A lifetime parameter names a region of the program during which a reference is valid. When two arguments share the name 'a, the compiler picks a single region that fits both. In practice that is the shorter of the two. This is what you want for longest, because the result may be either input.
It is too strict when the result depends on only one input. Here is a function that always returns its first argument but uses one lifetime for both:
fn first_of_one<'a>(x: &'a str, _y: &'a str) -> &'a str {
x
}
fn main() {
let a = String::from("alpha");
let result;
{
let b = String::from("beta");
result = first_of_one(a.as_str(), b.as_str());
} // b is dropped here
println!("{result}");
}
// error[E0597]: `b` does not live long enoughThe function body is fine. The signature is the problem. It tells the caller that result may borrow from b, so the compiler keeps b alive for as long as result is used. The signature claims a relationship that the body does not need.
Declaring several lifetime parameters
List more than one name in the angle brackets, separated by commas. Each name is an independent region unless you relate them.
fn first_of<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x
}
fn main() {
let a = String::from("alpha");
let result;
{
let b = String::from("beta");
result = first_of(a.as_str(), b.as_str());
} // b is dropped here, and that is fine
println!("{result}");
}The signature now states that the output is valid for 'a, and that 'b has nothing to do with the output. The borrow of b ends after the call returns, so dropping b early is legal.
A signature is a contract that the compiler checks in two directions:
- Inside the function: the body must not return anything that could outlive the promised region.
- At each call site: the caller must keep the data alive for the regions the signature names.
Fewer promises mean more freedom for callers, and the body must be able to keep every promise it makes.
Reading the signature as a dependency table
You can read a signature by asking which inputs each output depends on.
| Signature | What the caller learns |
|---|---|
| `fn f<'a>(x: &'a str, y: &'a str) -> &'a str` | The result may borrow from either input. Both must outlive its use. |
| `fn f<'a, 'b>(x: &'a str, y: &'b str) -> &'a str` | The result borrows only from `x`. `y` may end after the call. |
| `fn f<'a, 'b>(x: &'a str, y: &'b str) -> &'b str` | The result borrows only from `y`. |
| `fn f<'a, 'b>(x: &'a str, y: &'b str) -> usize` | Nothing is returned by reference, so neither lifetime escapes. |
The last row shows that lifetime names on arguments matter only when they connect to something else, such as the return type. An annotation that appears once is rarely needed, because elision can usually supply it.
When the body breaks the promise
Separate lifetimes also protect you from yourself. If the signature says the result depends on x, the body cannot return y:
fn pick_y<'a, 'b>(_x: &'a str, y: &'b str) -> &'a str {
y
}
// error: lifetime may not live long enough
// help: consider adding the following bound: `'b: 'a`The compiler cannot show that y stays valid for all of 'a, so it rejects the function. You have three fixes, and the right one depends on the intent:
- Change the return type to
&'b str, if the result really comes fromy. - Use one shared lifetime, if the result may come from either input and you accept the stricter contract.
- Add an outlives bound, described next.
Outlives bounds between lifetimes
The syntax 'b: 'a reads as "'b outlives 'a". It means 'b lasts at least as long as 'a. A reference valid for the longer region is also valid for the shorter one, so the compiler can treat a &'b str as a &'a str.
fn pick<'a, 'b: 'a>(x: &'a str, y: &'b str, use_first: bool) -> &'a str {
if use_first { x } else { y }
}
fn main() {
let long_lived = String::from("outer");
let result;
{
let short_lived = String::from("inner");
result = pick(&short_lived, &long_lived, false).len();
}
println!("{result}");
}Callers must supply an x and y such that y's region contains x's. The bound is a requirement on callers. In return, the body may return either argument as &'a str.
Most code does not need outlives bounds between two reference lifetimes. If the result may come from either input, a single shared lifetime is simpler and says nearly the same thing. A bound is mostly useful when you want to keep the two names separate for documentation or for other parts of the signature.
Multiple lifetimes in a struct
A struct that holds two references can use one lifetime parameter per reference. This matters when the references come from different places and are used differently.
struct Parser<'s, 'p> {
source: &'s str,
pattern: &'p str,
}
impl<'s, 'p> Parser<'s, 'p> {
fn first_match(&self) -> Option<&'s str> {
let source: &'s str = self.source;
let start = source.find(self.pattern)?;
Some(&source[start..start + self.pattern.len()])
}
}
fn main() {
let text = String::from("the quick brown fox");
let found;
{
let pat = String::from("quick");
let parser = Parser { source: &text, pattern: &pat };
found = parser.first_match();
} // parser and pat are dropped here
println!("{found:?}");
}The method returns Option<&'s str>. The result is a slice of the source text, so it is tied to 's. It is not tied to the borrow of self, and it is not tied to 'p. That is why found stays usable after both parser and pat are gone.
The elided version is stricter
Suppose you wrote the method with an elided return type:
fn first_match(&self) -> Option<&str> {
// ...
}Elision would then tie the result to &self. In main, found would borrow from parser, and using it after parser is dropped would fail with E0597. The explicit 's is what lets the result outlive the parser. Whenever a method returns data from a field, check whether the result should be tied to the struct borrow or to the lifetime stored in the field.
Choosing between one lifetime and several
| Situation | Use |
|---|---|
| The result may come from any of the inputs | One shared lifetime |
| The result comes from exactly one input | A separate lifetime for each input |
| A struct holds references from unrelated sources and methods return data from one source | One lifetime parameter per source |
| An input is used only during the call and never returned or stored | No named lifetime, so let elision handle it |
| You must return a value from `y` as if it were `x`'s lifetime | An outlives bound, or restructure to one lifetime |
Do not add lifetime parameters speculatively. Each extra parameter appears in every signature that mentions the type and makes the API harder to read. Add one when a real caller needs the looser contract, as the dropped-b example above did.
Errors you will see
- E0106, missing lifetime specifier. Elision cannot choose an output lifetime when there are several input references and no
&self. A function likefn pick(x: &str, y: &str) -> &strfails. Decide which input the result depends on and name the lifetimes accordingly. - E0597, borrowed value does not live long enough. A shared lifetime is forcing a short-lived input to live as long as the result. Check whether the signature should use separate lifetimes, as in
first_of. - "lifetime may not live long enough." The body returns something whose lifetime is not covered by the signature. Fix the return type, share the lifetime, or add an outlives bound.
Exercises
Exercise
This function compiles, but a caller cannot drop prefix while still using the result. Rewrite the signature so the result depends only on text.
fn strip<'a>(text: &'a str, prefix: &'a str) -> &'a str {
text.stripprefix(prefix).unwrapor(text)
}
Show answer
Use two lifetime parameters and tie the return value to text only:
fn strip<'a, 'b>(text: &'a str, prefix: &'b str) -> &'a str {
text.stripprefix(prefix).unwrapor(text)
}
The result is a slice of text (or text itself), so 'a is correct. prefix is only read during the call, so 'b does not reach the output and the caller may drop prefix right away.
Exercise
In the Parser<'s, 'p> example, you change first_match to return Option<&'p str> and return a slice of self.pattern. Does the main function still compile? Explain why or why not.
Show answer
Yes, the function body is valid, but the main function shown no longer compiles. The result is now tied to 'p, the lifetime of pat. pat is dropped at the end of the inner block, and found is printed after that, so the compiler reports E0597 for pat. The change moves the dependency from text to pat.