Sub topic 13
Lifetime elision rules
Every reference in Rust has a lifetime, but you rarely write one. This chapter explains why, and shows how the compiler fills in lifetimes for you. It also covers the cases where it can't.
This chapter assumes you know what a reference is, how the borrow checker works, and how to write a lifetime annotation like 'a on a function. The previous chapter covered those annotations.
Why elision exists
In early Rust, every reference in a function signature needed an explicit lifetime. Most signatures followed the same few patterns, so the Rust team encoded those patterns in the compiler. These patterns are the elision rules.
Elision is not inference. The compiler does not look inside the function body to work out lifetimes. It applies three fixed rules to the signature alone. If the rules produce a complete answer, you can leave the annotations out. If they don't, the compiler reports an error and asks you to write them.
Here is a function you have already written without annotations:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let text = String::from("ownership is rust's key idea");
println!("{}", first_word(&text));
}The compiler reads the signature as if you had written this:
fn first_word<'a>(s: &'a str) -> &'a str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let text = String::from("ownership is rust's key idea");
println!("{}", first_word(&text));
}Both versions mean the same thing. The returned slice lives no longer than the input.
Input and output lifetimes
Elision rules use two terms:
- An input lifetime is a lifetime on a parameter.
- An output lifetime is a lifetime on a return value.
Each elided lifetime position gets its own lifetime parameter. The rules decide what the output lifetime equals.
The three rules
The compiler applies these rules in order and stops once every reference has a lifetime.
- Each elided lifetime in a parameter becomes a distinct lifetime parameter. A function with one reference parameter gets one lifetime. A function with two gets two, and so on.
- If there is exactly one input lifetime, it is assigned to every elided output lifetime.
- If there are several input lifetimes and one of them is
&selfor&mut self, the lifetime ofselfis assigned to every elided output lifetime.
Rules 2 and 3 only assign output lifetimes. Rule 1 is the only one that creates lifetimes. If an output lifetime is still unknown after all three rules, compilation fails.
Rule 1 and 2 in action
Take fn first_word(s: &str) -> &str.
| Step | Signature |
|---|---|
| Written | `fn first_word(s: &str) -> &str` |
| After rule 1 | `fn first_word<'a>(s: &'a str) -> &str` |
| After rule 2 | `fn first_word<'a>(s: &'a str) -> &'a str` |
Every reference now has a lifetime, so elision succeeds.
When the rules fail
Now consider longest, which takes two references and returns one:
fn longest(x: &str, y: &str) -> &str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
println!("{}", longest("hello", "hi"));
}This does not compile. Rule 1 gives x and y separate lifetimes. Rule 2 does not apply, because there are two input lifetimes. Rule 3 does not apply, because there is no self. The output lifetime stays unknown. The compiler reports an error like missing lifetime specifier and notes that the return type contains a borrowed value, but the signature does not say whether it is borrowed from x or y.
The fix is the annotation from the previous chapter:
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("longer text");
let b = String::from("short");
println!("{}", longest(&a, &b));
}Rule 3: methods
Methods that take &self are the most common reason elision works in real code. Rule 3 assumes that a returned reference borrows from self, not from the other arguments.
struct Parser {
input: String,
}
impl Parser {
fn first_token(&self, fallback: &str) -> &str {
self.input.split_whitespace().next().unwrap_or(fallback)
}
}
fn main() {
let p = Parser { input: String::from("let x = 1") };
println!("{}", p.first_token("none"));
}This does not compile, and the reason is useful to understand. Rule 3 ties the output to &self. But the function may return fallback, which has a different lifetime. The compiler rejects the body with a lifetime may not live long enough error. The signature the compiler assumed does not match what the body does.
Here the signature must say what you mean:
struct Parser {
input: String,
}
impl Parser {
fn first_token<'a>(&'a self, fallback: &'a str) -> &'a str {
self.input.split_whitespace().next().unwrap_or(fallback)
}
}
fn main() {
let p = Parser { input: String::from("let x = 1") };
println!("{}", p.first_token("none"));
}Now the result is valid only while both self and fallback are. That is the honest contract for this body.
The opposite case works fine with elision. If the method only returns data from self, the default is exactly right:
struct Parser {
input: String,
}
impl Parser {
fn first_token(&self, _unused: &str) -> &str {
self.input.split_whitespace().next().unwrap_or("")
}
}
fn main() {
let p = Parser { input: String::from("let x = 1") };
println!("{}", p.first_token("ignored"));
}Elision in other places
The same ideas apply outside plain functions.
- In
implblocks, the anonymous lifetime'_says "a lifetime exists here, pick one". It is useful when a type has a lifetime parameter and you don't want to name it. - In return types such as
Excerpt<'_>,'_makes it visible that a borrow is involved without inventing a name. - Function pointer types and trait objects have their own defaults, such as
Box<dyn Trait>meaningBox<dyn Trait + 'static>. These are separate rules and are beyond this chapter.
This example uses '_ on a struct that holds a reference:
struct Excerpt<'a> {
part: &'a str,
}
impl Excerpt<'_> {
fn len(&self) -> usize {
self.part.len()
}
}
fn make(text: &str) -> Excerpt<'_> {
Excerpt { part: text }
}
fn main() {
let text = String::from("Call me Ishmael. Some years ago...");
let e = make(&text);
println!("{}", e.len());
}In make, rules 1 and 2 give text one lifetime and copy it to the output, so Excerpt<'_> means Excerpt<'a> with the same 'a.
How the rules guide your decisions
The diagram shows how the compiler decides whether you need to write a lifetime.
Use this checklist when you read a signature:
- Does the function return a reference? If not, you rarely need to think about lifetimes.
- Count the input references. One input means the output borrows from it.
- Check for
&self. If present, the output borrows fromselfunless you annotate otherwise. - If neither applies, annotate the signature yourself.
Common mistakes
- Expecting the body to influence the signature. The compiler checks the body against the signature. It never rewrites the signature to fit the body, as the
first_tokenexample showed. - Annotating when it isn't needed. Code like
fn first_word<'a>(s: &'a str) -> &'a stris correct but noisy. Leave it out when elision gives the same meaning. - Returning a reference to a local value. No annotation fixes this, because the value is dropped at the end of the function. Return an owned value such as
Stringinstead. - Assuming
'_means'static. It does not. It means "an elided lifetime", chosen by the same rules.
Exercise
Apply the three elision rules to fn pick(a: &str, b: &str) -> &str. Does it compile as written? If not, write a version that does and say what the annotation promises.
Show answer
It does not compile. Rule 1 gives a and b different lifetimes, rule 2 needs exactly one input lifetime, and rule 3 needs &self. The output lifetime is unknown. One fix is fn pick<'a>(a: &'a str, b: &'a str) -> &'a str. It promises that the result is valid only as long as both inputs are. If the function always returns a, a tighter fix is fn pick<'a>(a: &'a str, b: &str) -> &'a str.
Exercise
A method has the signature fn name(&self, prefix: &str) -> &str. Which input does the returned reference borrow from, and what must you do if the body sometimes returns prefix?
Show answer
Rule 3 ties the output to &self. If the body can return prefix, the compiler rejects it. Write explicit lifetimes, such as fn name<'a>(&'a self, prefix: &'a str) -> &'a str, so the result is tied to both.