In Rust, what is lifetime elision, and why does `fn first_line(text: &str) -> &str` compile without writing any lifetime?
answer
- fixed rules, signature only
- one reference in, reference out
- output borrows from that input
- expanded form names a single 'a
basics
~20 sLifetime 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 sEvery 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// 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
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.
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.
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.
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.