skip to content

Elision Rules

Three elision rules let most signatures skip lifetimes, and the &self rule decides what a method returns borrows from. Interviewers ask when elision applies and when it fails.

on this pageshow

questions

6

In Rust, what is lifetime elision, and why does `fn first_line(text: &str) -> &str` compile without writing any lifetime?

level: juniorimportance: must knowfreq 74%

answer

  1. fixed rules, signature only
  2. one reference in, reference out
  3. output borrows from that input
  4. expanded form names a single 'a

basics

~20 s

Lifetime elision is rustc filling in the lifetimes a function signature leaves out, by fixed rules. With exactly one input lifetime, the returned reference gets it, so first_line reads as fn first_line<'a>(text: &'a str) -> &'a str.

solid answer

~40 s

Every reference in a signature has a lifetime, but rustc lets you omit them where a fixed set of **elision rules** gives one answer. Each elided input lifetime becomes its own lifetime parameter, and if there is exactly one input lifetime it is assigned to every elided output. So `fn first_line(text: &str) -> &str` is read as `fn first_line<'a>(text: &'a str) -> &'a str`: the returned slice borrows from `text`, and callers must keep that string alive while they use the result. Elision is not general inference: rustc never looks at the body to decide. When the rules give no answer, as with two reference inputs and a reference output, it stops with `E0106` and you write the lifetime yourself.

code

rust · 18 lines
rust
// Elided: one input reference, so the output borrows from it.
fn first_line(text: &str) -> &str {
    text.lines().next().unwrap_or("")
}

// What rustc reads it as.
fn first_line_expanded<'a>(text: &'a str) -> &'a str {
    text.lines().next().unwrap_or("")
}

fn main() {
    let doc = String::from("Release notes\nFixed the parser");
    let title = first_line(&doc);
    let same = first_line_expanded(&doc);
    println!("{title} | {same}");
    // drop(doc); // uncommenting this is E0505: `doc` is still borrowed by `title`
    println!("{}", title.len());
}

go deeper

for a junior

Know that every reference has a lifetime, that elision fills omitted ones in by fixed rules, and write the expanded form of a one-input signature such as first_line.

for a middle

Explain that elision reads only the signature, never the body, and that counting input lifetime positions decides the output; show the E0106 case where the count gives no answer.

for a senior

Use the expanded signature to explain caller-side errors, such as E0505 when an owner is moved while a returned slice is still used, and say when spelling lifetimes out helps reviewers.

for a principal

Treat elided signatures as documentation: a team can turn on the elided_lifetimes_in_paths lint so every hidden borrow in a type path is spelled out where reviewers see it.

## What elision is Every reference type in Rust carries a **lifetime**: the region of the program in which the borrow is valid. In a function signature those lifetimes are generic parameters, written `'a`, `'b` and so on, and they describe how the borrows in the inputs relate to the borrows in the output. Writing them on every function would be noisy, because most signatures follow a handful of obvious patterns. **Lifetime elision** is the name for the small set of fixed rules that lets you leave lifetimes out where those patterns apply. It is deliberately limited: rustc applies the rules to the **signature alone**, never to the function body. The body is checked afterwards against the signature the rules produced. That is why elision is predictable: you can tell what an elided signature means just by reading it. Elision is also why most Rust signatures you read carry no lifetimes at all. Getters, helpers that return a slice of their argument, and methods that return a reference into a collection all fit one of the rules. An explicit `'a` in a signature is therefore a signal: the borrow relationship is less obvious than usual, and the author had to state it. ## How rustc reads `first_line` For `fn first_line(text: &str) -> &str`, rustc works through the signature in order: 1. It finds every **input lifetime position**. `text: &str` has one: the lifetime of the `&`. Because it is elided, it becomes a fresh lifetime parameter, call it `'a`. 2. It counts the input lifetimes. There is **exactly one**, so that lifetime is assigned to every elided lifetime in the output. 3. The result is the expanded signature below, which is what the type checker and the borrow checker actually see. ```rust fn first_line(text: &str) -> &str { /* ... */ } // elided fn first_line<'a>(text: &'a str) -> &'a str { /* ... */ } // expanded ``` The two forms are the same function type. Writing the lifetime out changes readability, never meaning. ## What the filled-in lifetime promises The expanded signature makes a promise in both directions: - **To the body:** the function may return only data borrowed from `text`, or data that lives at least as long, such as a string literal. `unwrap_or("")` is fine because a literal lives for the whole program. - **To callers:** the returned `&str` keeps the argument borrowed. If a caller writes `let title = first_line(&doc);` and then calls `drop(doc)` while `title` is still used, rustc rejects it with ``error[E0505]: cannot move out of `doc` because it is borrowed``. - **Parameters without references do not count.** `fn clip(line: &str, limit: usize) -> &str` still elides, because `limit` has no lifetime position and `line` supplies the only input lifetime. ## Where the rules apply | Place | Elision? | |---|---| | Function items and methods | Yes, with the rules above | | Function pointer types such as `fn(&str) -> &str` | Yes | | `Fn`, `FnMut`, `FnOnce` sugar such as `impl Fn(&str) -> &str` | Yes | | Impl headers such as `impl fmt::Display for TextBuffer<'_>` | Yes, every lifetime there is an input; a path with its lifetime left out entirely is `E0726` | | Struct fields, enum variants, type aliases | No: a bare `&str` is `E0106` | | `const` and `static` items | Elided reference lifetimes are `'static` | The function-pointer and closure-trait cases produce a lifetime that holds for every input, which is a higher-ranked lifetime; that mechanism has its own material. ## When elision is not enough Elision covers the common shapes, not all of them. When an elided output lifetime matches no rule, rustc refuses to guess: ```rust fn pick(a: &str, b: &str) -> &str { a } // error[E0106]: missing lifetime specifier // help: this function's return type contains a borrowed value, but the // signature does not say whether it is borrowed from `a` or `b` ``` The same happens with no input lifetime at all, as in `fn default_name() -> &str`, where rustc says there is no value for it to be borrowed from. In those cases you name the lifetime and state which input the output depends on; writing those annotations is covered with explicit lifetime parameters. Two takeaways for interviews: - Elision is shorthand for one specific expanded signature, chosen by counting input lifetime positions. - It never extends a borrow, never defaults a function output to `'static` and never lets a function return a reference to its own local variable.

  • Does lifetime elision ever make a signature accept code that the expanded form would reject?
    No. Elision is pure shorthand: rustc rewrites the elided signature into exactly one expanded signature before checking anything, so both forms type-check identically, produce the same errors and mean the same thing to callers. The difference is readability, which is why a signature whose borrow relationship matters to reviewers is sometimes written out even where elision applies.
  • Why does `fn default_name() -> &str` fail even though its body returns a string literal?
    With no input lifetime there is nothing for the output to borrow from, so no rule applies and rustc reports `E0106`, saying the return type contains a borrowed value "but there is no value for it to be borrowed from". It suggests `&'static str`, right for a literal, or returning an owned `String`. Elision never defaults a function's output to `'static`.
  • Does `fn clip(line: &str, limit: usize) -> &str` elide, given that it has two parameters?
    Yes. The rules count lifetime positions, not parameters. `limit: usize` contains no lifetime, so `line` supplies the only input lifetime and the returned slice is tied to `line`. Add a second reference parameter and the same output would become `E0106`.

  • Elision means rustc reads the function body to see which input is returned.
  • References in an elided signature have no lifetime at all.
  • An elided return lifetime defaults to 'static in a function signature.
  • Elision lets a function return a reference to one of its local variables.
  • A struct field holding a reference can leave its lifetime out like a parameter.
open as a page

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%

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.

open as a page

In Rust, what does the anonymous lifetime `'_` mean in `impl fmt::Display for TextBuffer<'_>` and in a return type such as `SplitWhitespace<'_>`?

level: middleimportance: should knowfreq 40%

basics

~20 s

'_ is the anonymous lifetime: an elided lifetime written out. In an impl header each '_ becomes a fresh lifetime parameter; in a function signature it follows the elision rules, so SplitWhitespace<'_> returned from a &self method borrows from self.

open as a page

Which Rust function signatures make lifetime elision fail with E0106, and how should you judge the fix rustc suggests?

level: middleimportance: should knowfreq 55%

basics

~20 s

E0106 appears when an elided output lifetime matches no rule: no input lifetime, several input lifetimes with no &self receiver, or two positions inside one parameter. rustc's suggested lifetime compiles but can over-constrain; name only the input the output really borrows from.

open as a page

Why does the Rust method `fn line_or(&self, n: usize, fallback: &str) -> &str` fail to compile when it may return `fallback`?

level: middleimportance: should knowfreq 50%

basics

~20 s

Elision gives the output the lifetime of &self, while fallback gets its own unrelated lifetime, so returning fallback breaks the signature: lifetime may not live long enough. Name one lifetime on &self, fallback and the output, or return only data from self.

open as a page

On a Rust `TextBuffer<'a>` holding `&'a str`, why does `TextBuffer::new(&src).first_line()` fail with E0716 when `first_line(&self) -> &str` relies on elision?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Elision ties first_line's result to the borrow of self, the temporary TextBuffer, not to 'a, the source text. The temporary is freed at the end of the let statement, so the result cannot be used afterwards: E0716. Returning &'a str fixes it.

open as a page