skip to content

What are Rust's three lifetime elision rules, and how does the `&self` rule decide what a method's returned reference borrows from?

level: middleimportance: must knowfreq 70%

answer

  1. inputs first, then outputs
  2. each elided input gets its own
  3. exactly one input lifetime wins
  4. the receiver outranks other inputs

basics

~20 s

Each elided input lifetime becomes its own parameter; if there is exactly one input lifetime, every elided output gets it; in a method taking &self or &mut self, elided outputs get the receiver's lifetime. Any other elided output is error E0106.

solid answer

~40 s

rustc applies three rules to a signature. **Rule 1:** every elided lifetime in an input position becomes a distinct lifetime parameter. **Rule 2:** if there is exactly one input lifetime, elided or written, it is assigned to all elided output lifetimes. **Rule 3:** if the receiver is `&self` or `&mut self`, its lifetime is assigned to all elided outputs, however many other reference parameters there are. So `fn first_field(&self, sep: &str) -> &str` returns something borrowed from `self`, not from `sep`, and the result may outlive the `sep` argument. When no rule gives an output its lifetime, eliding it is `E0106`. The rules count lifetime positions: a `usize` parameter adds none, while `&mut Vec<&str>` adds two.

code

rust · 30 lines
rust
struct TextBuffer {
    text: String,
}

impl TextBuffer {
    // Rule 1 + rule 3: `&self` and `sep` get distinct lifetimes;
    // the output takes the lifetime of `&self`.
    fn first_field(&self, sep: &str) -> &str {
        self.text.split(sep).next().unwrap_or("")
    }

    // Written out, the same signature is:
    fn first_field_expanded<'s, 'p>(&'s self, sep: &'p str) -> &'s str {
        self.text.split(sep).next().unwrap_or("")
    }
}

// Rule 2: exactly one input lifetime (`line`), `limit` has none.
fn clip(line: &str, limit: usize) -> &str {
    &line[..line.len().min(limit)]
}

fn main() {
    let buf = TextBuffer { text: String::from("id,name,email") };
    let field = {
        let sep = String::from(",");
        buf.first_field(&sep) // `sep` is dropped here; the result only borrows `buf`
    };
    println!("{field} {} {}", buf.first_field_expanded(","), clip("abcdef", 3));
}

go deeper

for a junior

Recite the three rules in order and apply rule 2 to a helper taking one string slice and returning a slice of it.

for a middle

Expand a method signature by hand, showing the output follows &self even beside other reference parameters, and explain why its result may outlive a temporary argument.

for a senior

Spot signatures where the receiver rule picks the wrong source, such as returning a slice of an argument, and fix them with one named lifetime rather than an allocation.

for a principal

Recognise that the receiver rule ties every returned borrow to the whole value, which decides whether callers can mutate a type while holding results from its getters.

## Input and output lifetime positions The elision rules work on **lifetime positions**: every place in a type where a lifetime could be written. - `&'a T` and `&'a mut T` each have one position, the lifetime of the reference. - A type with lifetime parameters, such as `TextBuffer<'a>` or `std::str::Lines<'a>`, has one position per parameter, even when you write it as `TextBuffer<'_>` or leave the parameter out. - Positions nest: `&mut Vec<&str>` has two, the outer `&mut` and the inner `&str`. - Positions in the parameter types are **inputs**; positions in the return type are **outputs**. - For a method, the lifetimes declared on its `impl` header are **not** inputs of the method. Only the method's own parameter types count. ## The three rules rustc applies the rules in this order: 1. **Each elided input lifetime becomes a distinct lifetime parameter.** `fn f(a: &str, b: &str)` has two independent parameters, not one shared one. 2. **If there is exactly one input lifetime, elided or written, it is assigned to all elided output lifetimes.** 3. **If the receiver has type `&Self` or `&mut Self`, the receiver's lifetime is assigned to all elided output lifetimes**, whatever other input lifetimes exist. If an output lifetime is elided and neither rule 2 nor rule 3 applies, the signature is an error: `error[E0106]: missing lifetime specifier`. Rule 1 alone never fails; a function with no reference in its return type, such as `fn print(line: &str)`, needs only rule 1. Rules 2 and 3 can both apply. In `fn text_mut(&mut self) -> &mut String` the receiver is the only input lifetime, so both give the same answer. When they would differ, because a method has `&self` plus other reference parameters, rule 2 does not apply at all and rule 3 decides. ## The `&self` rule in practice Most methods that return a reference return something inside `self`: a field, a slice of a buffer, an element of a collection. Rule 3 encodes that. Without it, every method taking `&self` plus one more reference parameter would hit `E0106`. ```rust impl TextBuffer { fn first_field(&self, sep: &str) -> &str { /* ... */ } // means: fn first_field<'s, 'p>(&'s self, sep: &'p str) -> &'s str { /* ... */ } } ``` Because the output is tied only to `'s`, a caller may pass a short-lived separator, let it drop, and keep using the field. The same rule also limits the method: if the body tried to return `sep`, the borrow checker would reject it, because the signature promised data borrowed from `self`. ## Worked expansions | Elided signature | Expanded | Rule that decides the output | |---|---|---| | `fn print(line: &str)` | `fn print<'a>(line: &'a str)` | none needed, rule 1 only | | `fn clip(line: &str, limit: usize) -> &str` | `fn clip<'a>(line: &'a str, limit: usize) -> &'a str` | rule 2 | | `fn first_field(&self, sep: &str) -> &str` | `fn first_field<'s, 'p>(&'s self, sep: &'p str) -> &'s str` | rule 3 | | `fn text_mut(&mut self) -> &mut String` | `fn text_mut<'s>(&'s mut self) -> &'s mut String` | rules 2 and 3 agree | | `fn pick(a: &str, b: &str) -> &str` | none | E0106: two inputs, no receiver | | `fn last_word(words: &mut Vec<&str>) -> &str` | none | E0106: two positions in one parameter | ## Details that trip people up - **Positions, not distinct names.** `fn both<'a>(a: &'a str, b: &'a str) -> &str` uses one named lifetime twice, yet rustc 1.99 still rejects the elided output with `E0106` and suggests writing `&'a str`. - **Only `&self` and `&mut self` trigger rule 3.** A by-value `self` or `self: Box<Self>` has no receiver lifetime; such a method falls back to rule 2, so `fn f(self: Box<Self>, x: &str) -> &str` borrows from `x`, and a second reference parameter makes it `E0106`. - **Rule 3 is a default, not a reading of the body.** It assigns the receiver's lifetime even when the body returns another argument; that case needs a named lifetime. - **The same rules apply to function pointer types and closure-trait sugar** such as `fn(&str) -> &str`, where they yield a lifetime that holds for every input. - **The three rules are not tied to an edition**: the signatures in the table above elide, or fail with `E0106`, the same way when compiled as 2015-edition or 2024-edition code.

  • Why does the `&self` rule exist instead of methods following the free-function rules?
    Methods that return a reference usually return part of `self`. Under the free-function rules, any method with `&self` plus another reference parameter would have two input lifetimes and fail with `E0106`, forcing annotations onto ordinary getters and lookups. Rule 3 encodes the common case; a method that really returns data from another argument overrides it with a named lifetime.
  • Does rule 2 count distinct lifetimes or lifetime positions?
    Positions. `fn both<'a>(a: &'a str, b: &'a str) -> &str` names one lifetime but uses it in two positions, and rustc 1.99 rejects the elided output with `E0106`, suggesting `&'a str`. Likewise `&mut Vec<&str>` holds two positions inside one parameter, so `fn last_word(words: &mut Vec<&str>) -> &str` fails as well.
  • What does rule 3 do for a method whose receiver is `self: Box<Self>`?
    Nothing: the receiver rule applies to `&Self` and `&mut Self` receivers. With `self: Box<Self>` the receiver contributes no lifetime, so `fn f(self: Box<Self>, x: &str) -> &str` uses rule 2 and borrows from `x`, while adding a second reference parameter makes the elided output `E0106`.

  • The &self rule applies only when the method has no other reference parameters.
  • With two reference parameters, rustc ties the output to the first one.
  • A usize or other non-reference parameter counts as an input lifetime.
  • Using the same named 'a on both inputs makes an elided output legal.
  • Rule 3 ties the output to whichever argument the method body returns.