Sub topic 2
Relating References with Multiple Lifetime Parameters
This chapter assumes ownership, moves, borrowing, String, &str, structs, and basic generics. A lifetime is the span of code during which a reference is valid. Lifetime annotations describe relationships between references. They do not extend a value’s lifetime.
Multiple lifetime parameters
Use different lifetime names when references may remain valid for different spans. In this example, the result depends only on x:
fn first_of<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x
}
fn main() {
let first = String::from("first");
let result;
{
let second = String::from("second");
result = first_of(first.as_str(), second.as_str());
}
println!("{result}");
}The returned reference has lifetime 'a, so second may be dropped after the call. By contrast, a function such as longest<'a>(x: &'a str, y: &'a str) -> &'a str promises that its result is valid only while both inputs are valid.
| Signature relationship | Meaning |
|---|---|
| `&'a T, &'a T -> &'a T` | The result may depend on both inputs |
| `&'a T, &'b T -> &'a T` | The result depends on the first input |
Lifetime elision
Lifetime elision means the compiler fills in common annotations. The rules include:
- Each input reference gets its own lifetime.
- With one input lifetime, that lifetime becomes the output lifetime.
- In a method, an elided output lifetime normally comes from
&selfor&mut self.
Therefore these signatures mean the same thing:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn first_word_explicit<'a>(s: &'a str) -> &'a str {
s.split_whitespace().next().unwrap_or("")
}Elision cannot guess which input controls an output when several unrelated references exist. Add explicit parameters in that case.
Structs that borrow data
A struct containing a reference must declare the lifetime of that reference:
struct Excerpt<'a> {
part: &'a str,
}Excerpt<'a> cannot outlive the string that provides part.
Lifetimes in impl blocks and methods
Repeat the lifetime parameter on the impl block. Method elision ties the returned reference to self:
impl<'a> Excerpt<'a> {
fn part(&self) -> &str {
self.part
}
}The returned &str cannot outlive the Excerpt, its part, or the original string.
Exercise
Why does first_of use separate lifetimes for its two inputs?
Show answer
Because the result refers only to x, so it need not remain valid while y is alive.