Sub topic 9
When You Can Omit Lifetimes: Elision Rules
Most Rust functions that take and return references have no lifetime annotations. This chapter explains why. Lifetime elision is a small set of fixed rules that the compiler applies to a function signature to fill in lifetimes you left out. Knowing the rules tells you when you can leave annotations off, and what to do when the compiler asks for them.
This chapter assumes you know shared and mutable references, the borrowing rules, and the explicit 'a syntax from the previous chapter.
Elision is not inference
Elision is mechanical text expansion on the signature. The compiler does not read your function body to decide which input a returned reference comes from. It applies three rules to the signature, and if they leave an output lifetime undetermined, it reports an error. This keeps signatures a reliable contract. A caller can understand a function from its signature alone, and changing the body cannot silently change what callers are allowed to do.
Two terms matter here:
- An input lifetime position is any place a lifetime can appear in a parameter type. Examples are
&str,&mut Vec<i32>, andExcerpt<'_>. - An output lifetime position is the same thing in the return type.
Elision only applies to fn signatures, method signatures, and impl headers. Struct field types never get elided lifetimes. Those must be written out.
The three rules
- Each elided lifetime in the input positions becomes its own separate lifetime parameter.
- If there is exactly one input lifetime position, that lifetime is assigned to every elided output lifetime.
- If there are several input positions but one of them is
&selfor&mut self, the lifetime ofselfis assigned to every elided output lifetime.
If the compiler finishes these rules and any output lifetime is still unassigned, it stops with error E0106, "missing lifetime specifier".
Rule 2 in practice
Here is the first_word function from earlier, written the way you normally see it:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let sentence = String::from("borrowing is useful");
let word = first_word(&sentence);
println!("{word}");
}Rule 1 gives the parameter a fresh lifetime. Rule 2 sees one input position and gives the return type the same lifetime. The compiler treats 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 sentence = String::from("borrowing is useful");
let word = first_word(&sentence);
println!("{word}");
}Both versions compile to the same thing. The annotation adds no behavior. It only documents a relationship the compiler already knows.
When rule 2 fails: several inputs
With two reference parameters, rule 1 creates two lifetimes and rule 2 does not apply. Rule 3 needs a self, and a free function has none.
// Does not compile: E0106, missing lifetime specifier.
fn longest(x: &str, y: &str) -> &str {
if x.len() >= y.len() { x } else { y }
}The error message says 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 explicit annotation you saw earlier: fn longest<'a>(x: &'a str, y: &'a str) -> &'a str.
The same happens when one parameter hides several lifetimes. A tuple (&str, &str) is a single parameter but has two input lifetime positions, so fn pick(pair: (&str, &str)) -> &str also fails. Count lifetime positions, not parameters.
When there are no inputs
A function with a reference in its return type and no reference inputs has nothing to borrow from. Elision cannot help, and the only valid lifetime is usually 'static:
fn greeting() -> &'static str {
"hello"
}
fn main() {
println!("{}", greeting());
}String literals live for the whole program, so 'static is accurate here. Writing fn make() -> &str is rejected, which is the dangling-reference case from the earlier chapter showing up at the signature level.
Rule 3: methods and `&self`
Methods are the main reason rule 3 exists. A method that returns a reference nearly always returns something borrowed from the object, so the rule assumes that:
struct Config {
name: String,
}
impl Config {
fn name(&self) -> &str {
&self.name
}
fn label(&self, prefix: &str) -> &str {
let _ = prefix;
&self.name
}
}
fn main() {
let c = Config { name: String::from("server") };
println!("{} {}", c.name(), c.label("x"));
}In label, there are two input positions: &self and prefix. Rule 3 ties the result to self. The returned reference lives as long as the borrow of c, and it does not depend on prefix. This lets a caller pass a temporary string as prefix without trouble.
The gotcha: returning the other argument
Rule 3 picks self even when the body returns the other parameter. The compiler does not look at the body, so it reports an error there:
struct Config {
name: String,
}
impl Config {
// Does not compile: the elided output lifetime is tied to self,
// but the body returns data borrowed from `candidate`.
fn choose(&self, candidate: &str) -> &str {
if candidate.is_empty() { &self.name } else { candidate }
}
}The compiler reports "lifetime may not live long enough". It says the function was supposed to return data with the lifetime of one reference but returns data with the lifetime of another. You must say what you mean. Here the result may come from either input, so both get the same name:
struct Config {
name: String,
}
impl Config {
fn choose<'a>(&'a self, candidate: &'a str) -> &'a str {
if candidate.is_empty() { &self.name } else { candidate }
}
}
fn main() {
let c = Config { name: String::from("default") };
println!("{}", c.choose(""));
println!("{}", c.choose("custom"));
}If the method returns only candidate, then fn choose<'a>(&self, candidate: &'a str) -> &'a str is the better signature. It does not tie the result to self, so callers can keep the result after releasing the borrow of the object.
The anonymous lifetime `'_`
The '_ lifetime means "an elided lifetime, filled in by the rules." You need it in places where eliding a lifetime entirely would hide that a reference is involved. The main case is a type that has a lifetime parameter, such as the struct from the earlier chapter:
struct Excerpt<'a> {
part: &'a str,
}
impl Excerpt<'_> {
fn part(&self) -> &str {
self.part
}
}
fn excerpt_of(text: &str) -> Excerpt<'_> {
Excerpt { part: text.split('.').next().unwrap_or("") }
}
fn main() {
let text = String::from("Call me Ishmael. Some years ago...");
let e = excerpt_of(&text);
println!("{}", e.part());
}Three uses appear here:
impl Excerpt<'_>says the impl works for any lifetime, and we do not need to name it. This is shorter thanimpl<'a> Excerpt<'a>when'ais not used in the body.Excerpt<'_>in the return type ofexcerpt_ofshows the returned value holds a borrow. Rule 2 connects it totext.Excerptwith no<'_>also compiles in a return type, but it hides the borrow. Writing'_is the recommended style, and therust_2018_idiomslint group can enforce it.
What elision cannot do
| Situation | Elision works? | What to do |
|---|---|---|
| One reference parameter, reference returned | Yes (rule 2) | Omit lifetimes |
| `&self` method returning a reference | Yes (rule 3) | Omit lifetimes |
| Two or more reference parameters in a free function, reference returned | No | Name the lifetimes |
| Method returns data from a non-self parameter | Compiles, but ties to `self` | Name the lifetime on that parameter |
| Reference returned, no reference parameters | No | Use `'static` or return an owned value |
| Struct field holding a reference | Never | Declare `struct S<'a>` |
If the table sends you to "name the lifetimes" often, consider the alternative from the chapter on choosing parameter types. Returning an owned String instead of a borrowed &str removes the question entirely, at the cost of an allocation.
Checklist for reading a signature
- Count the lifetime positions in the parameters, including those hidden inside types such as
Excerpt<'_>or tuples. - If there is exactly one, the output borrows from it.
- If there are several and a
&selfor&mut selfis present, the output borrows fromself. - Otherwise, the compiler will ask you to write lifetimes.
Exercise
The function fn pick(a: &str, b: &str) -> &str is rejected with E0106. Write a signature that compiles and says the result may come from either argument. Then write a different signature that says the result always comes from a only.
Show answer
For either argument: fn pick<'a>(a: &'a str, b: &'a str) -> &'a str. For a only: fn pick<'a>(a: &'a str, b: &str) -> &'a str. In the second form, b gets its own elided lifetime by rule 1, so the result does not depend on it.
Exercise
Given impl Config { fn first(&self, other: &str) -> &str { other } }, which rule assigns the output lifetime, and why does the body fail to compile? How do you fix it?
Show answer
Rule 3 assigns the lifetime of self to the output, because there are two input positions and one is &self. The body returns other, which has a different lifetime, so the compiler reports that the lifetime may not live long enough. Fix it by naming the lifetime on other and the return type: fn first<'a>(&self, other: &'a str) -> &'a str.
Exercise
Why does fn make() -> &str fail while fn make() -> &'static str { "hi" } compiles?
Show answer
With no input lifetime positions, none of the three elision rules can supply an output lifetime, so the compiler reports a missing lifetime specifier. A string literal lives for the whole program, so 'static is a correct explicit lifetime for the return value.