Sub topic 7
Lifetime elision: when you can leave annotations out
This chapter assumes you can read basic Rust (functions, structs, impl blocks, generics). It also assumes you know the borrowing rules for &T and &mut T, and that you have seen the <'a> syntax from the previous chapters. Here you will learn the three rules the compiler uses to fill in lifetimes, when they apply, and what to do when they fail.
What elision is
Most functions that take and return references have no visible lifetime annotations. That is not because the compiler guesses from your function body. It applies a fixed set of rules to the signature only. This is called lifetime elision. The compiler writes the explicit annotations for you, and if the rules cannot produce an unambiguous answer, it stops and asks you for them.
Here is a function you can write without any annotation, next to what the compiler infers:
// What you write:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
// What the compiler infers after elision:
fn first_word_explicit<'a>(s: &'a str) -> &'a str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
println!("{}", first_word("hello world"));
println!("{}", first_word_explicit("goodbye world"));
}Elision is a convenience for common patterns. It does not change the meaning of the signature. Both versions above are the same function type.
The three rules
Elision works with two kinds of positions. Input lifetimes are the lifetimes in parameter types. Output lifetimes are the lifetimes in the return type. The rules run in order:
- Each elided lifetime in the parameters becomes its own distinct lifetime parameter.
- If there is exactly one input lifetime, elided or not, it is assigned to every elided output lifetime.
- If one of the parameters is
&selfor&mut self, the lifetime of that borrow is assigned to every elided output lifetime.
If the output still has an elided lifetime after the rules have run, the compiler reports error E0106 (missing lifetime specifier).
Rule 1 alone handles functions that return no references. These two signatures are identical:
fn show(a: &str, b: &str) {
println!("{a} {b}");
}
fn show_explicit<'a, 'b>(a: &'a str, b: &'b str) {
println!("{a} {b}");
}
fn main() {
show("x", "y");
show_explicit("x", "y");
}The two parameters get separate lifetimes. Nothing links them, and nothing needs to.
Where the rules run out
When two or more inputs carry lifetimes and there is no self, rules 2 and 3 do not apply. The classic example is longest:
// Does not compile:
// fn longest(x: &str, y: &str) -> &str {
// if x.len() > y.len() { x } else { y }
// }
// error[E0106]: missing lifetime specifierThe signature does not say whether the result borrows from x, from y, or from either one. The compiler will not read the body to find out. This matters because callers are checked against the signature only. The fix is to state the relationship:
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");
println!("{}", longest(&a, &b));
}A function with no reference inputs and a reference output also fails, because there is nothing to borrow from. Either return an owned value such as String, or return &'static str if the data is a literal.
fn greeting() -> &'static str {
"hello"
}
fn main() {
println!("{}", greeting());
}Rule 3 in methods
In a method, the compiler assumes the returned reference borrows from self. This is usually right, because methods typically hand out parts of the thing they belong to. It also means a method with several reference parameters still compiles without annotations:
struct Parser<'a> {
input: &'a str,
}
impl<'a> Parser<'a> {
// Elided: the result borrows from &self, not from `prefix`.
fn input_short(&self, prefix: &str) -> &str {
println!("prefix: {prefix}");
self.input
}
// Explicit: the result lives as long as the original text.
fn input_long(&self) -> &'a str {
self.input
}
}
fn main() {
let text = String::from("key=value");
let kept;
{
let p = Parser { input: &text };
println!("{}", p.input_short("p"));
kept = p.input_long();
}
println!("{kept}");
}This program shows the main gotcha of rule 3. input_short returns a reference tied to the borrow of p, so its result cannot outlive p. If kept were assigned from input_short, the program would fail with E0597 (p does not live long enough). input_long names 'a, the lifetime of the underlying text, so kept is still valid after p is gone. Elision picks the safe choice, but not always the most flexible one.
When the result does not come from self
Rule 3 can also be wrong in the other direction. If a method returns data from another parameter, the elided signature claims the wrong source, and the compiler rejects the body:
struct Parser<'a> {
input: &'a str,
}
impl<'a> Parser<'a> {
// fn pick(&self, other: &str) -> &str { other }
// error: lifetime may not live long enough
fn pick<'b>(&self, other: &'b str) -> &'b str {
other
}
}
fn main() {
let p = Parser { input: "abc" };
println!("{} {}", p.pick("xyz"), p.input);
}The error here is not E0106. The signature was complete, but it said something the body does not do.
Elision in impl headers and paths: `'_`
The anonymous lifetime '_ means "infer a lifetime here". It is useful where you do not need to name the lifetime.
struct Parser<'a> {
input: &'a str,
}
// No need to write impl<'a> Parser<'a> when 'a is never used by name.
impl Parser<'_> {
fn len(&self) -> usize {
self.input.len()
}
}
// Makes the borrow visible in the return type.
fn make_parser(s: &str) -> Parser<'_> {
Parser { input: s }
}
fn main() {
let p = make_parser("hello");
println!("{}", p.len());
}Parser<'_> in the return type follows the same rules as &str. With one input lifetime, rule 2 gives it to the output. Writing -> Parser without '_ also compiles, but it hides that the value borrows something. Writing '_ makes the borrow visible to the reader.
What elision does not cover
| Place | Elision allowed? | Why |
|---|---|---|
| Function and method signatures | Yes | The three rules apply. |
| `impl` headers | Partly, with `'_` | `impl Trait for Type<'_>` is fine. |
| Struct and enum fields | No | There are no inputs to choose from, so `&str` in a field is E0106. |
| `static` and `const` items | Yes, as `'static` | The default for references there is `'static`. |
| `Fn(&str) -> &str` bounds | Yes, with different meaning | Each elided input is higher-ranked. A later chapter covers this. |
| `Box<dyn Trait>` | Defaults to `'static` | `&'a dyn Trait` defaults to `'a` instead. |
For structs, you must always write the parameter:
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let text = String::from("Call me Ishmael. Some years ago...");
let e = Excerpt { part: text.split('.').next().unwrap_or("") };
println!("{}", e.part);
}Choosing between elision and explicit lifetimes
- Start with no annotations. If the code compiles and the relationship is what you intend, leave it.
- If you get E0106, decide which input the output borrows from, then name only the lifetimes you need.
- If a method returns data that must outlive the borrow of
self, name the struct's lifetime in the return type, asinput_longdoes. - Prefer
'_inimplheaders and return types when you do not need to refer to the lifetime by name. - If the output needs a lifetime that is unrelated to any input, return an owned type or
'static.
Exercises
Exercise
For each signature, say whether it compiles without explicit lifetimes, and which rule applies. (a) fn trim_it(s: &str) -> &str. (b) fn pick(a: &str, b: &str) -> &str. (c) fn name(&self, default: &str) -> &str inside an impl block.
Show answer
(a) Compiles. Rule 1 creates one input lifetime and rule 2 assigns it to the output. (b) Fails with E0106. There are two input lifetimes and no self, so neither rule 2 nor rule 3 applies. Write fn pick<'a>(a: &'a str, b: &'a str) -> &'a str. (c) Compiles. Rule 3 ties the output to the borrow of &self. If the body returns default, you get a "lifetime may not live long enough" error instead, and you must write fn name<'b>(&self, default: &'b str) -> &'b str.
Exercise
A struct Parser<'a> has a method fn input(&self) -> &str { self.input }. A caller stores the result, drops the parser, and then uses the result, which fails with E0597. How do you change the method so the caller's code compiles, and why does it work?
Show answer
Change the return type to &'a str, which gives fn input(&self) -> &'a str. Elision rule 3 tied the original result to the borrow of self, so it could not outlive the parser. Naming 'a ties the result to the underlying text, which lives longer than the parser value.