skip to content

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%

answer

  1. a lifetime you need not name
  2. fresh parameter in impl headers
  3. follows elision in signatures
  4. makes a hidden borrow visible

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.

solid answer

~40 s

`'_` asks rustc to fill in a lifetime by the usual rules instead of naming it. In an **impl header** such as `impl fmt::Display for TextBuffer<'_>`, every lifetime is an input, so each `'_` becomes a fresh, distinct parameter: shorthand for `impl<'a> fmt::Display for TextBuffer<'a>` when the body never names `'a`. Leaving the lifetime out there entirely is `error[E0726]: implicit elided lifetime not allowed here`. In a **signature**, `'_` behaves like an omitted lifetime: in an input it is a new parameter, in an output it takes the lifetime the rules assign, so `fn words(&self) -> SplitWhitespace<'_>` borrows from `self`. Its main job is visibility: since Rust 1.89 the warn-by-default `mismatched_lifetime_syntaxes` lint flags `fn lines(&self) -> std::str::Lines`, which hides the borrow in a path, and suggests `Lines<'_>`.

code

rust · 25 lines
rust
use std::fmt;

struct TextBuffer<'a> {
    src: &'a str,
}

// `'_` in an impl header: a fresh, unnamed lifetime parameter.
impl fmt::Display for TextBuffer<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} lines", self.src.lines().count())
    }
}

impl TextBuffer<'_> {
    // `'_` in the return type follows the elision rules: it is `&self`'s lifetime.
    fn words(&self) -> std::str::SplitWhitespace<'_> {
        self.src.split_whitespace()
    }
}

fn main() {
    let doc = String::from("fix parser\nship release");
    let buf = TextBuffer { src: &doc };
    println!("{buf}: {:?}", buf.words().collect::<Vec<_>>());
}

go deeper

for a junior

Recognise '_ as a placeholder lifetime rustc fills in, and write impl fmt::Display for TextBuffer<'_> when the impl never needs to name the lifetime.

for a middle

Explain the two meanings: a fresh parameter for each '_ in impl headers and inputs, the elision-assigned lifetime in outputs, and E0726 when an impl header omits it.

for a senior

Use '_ to keep borrows visible in signatures, act on mismatched_lifetime_syntaxes warnings, and switch to impl<'a> once a method must return data tied to 'a.

for a principal

Decide whether a codebase enables elided_lifetimes_in_paths through rust_2018_idioms, trading some noise for signatures where every hidden borrow is visible in review.

## What `'_` is `'_` is the **anonymous lifetime**, also called the placeholder lifetime. Writing it tells rustc: there is a lifetime here, fill it in the same way you would if I had omitted it. It is never a specific lifetime of its own, and it is not `'static`. You use it where a type has a lifetime parameter and you want the position to be visible without inventing a name. There are two contexts where it means slightly different things, and interviewers usually probe the difference. ## In impl headers In an impl header, every lifetime position is an **input**, so each `'_` becomes a **fresh, distinct lifetime parameter** of the impl: ```rust impl fmt::Display for TextBuffer<'_> { /* ... */ } // is shorthand for impl<'a> fmt::Display for TextBuffer<'a> { /* ... */ } ``` Key facts: - Two `'_` in one impl header are two different lifetimes, never one shared one. - The lifetime cannot be referred to inside the impl, because it has no name. When a method must return data tied to it, such as `fn first_line(&self) -> &'a str`, declare it: `impl<'a> TextBuffer<'a>`. - Omitting the lifetime of a type entirely in an impl header is an error: `impl fmt::Display for TextBuffer` gives `error[E0726]: implicit elided lifetime not allowed here`, and rustc's help suggests `TextBuffer<'_>`. - Inside `fmt`, the parameter `f: &mut fmt::Formatter<'_>` uses the same placeholder for the formatter's lifetime parameter. ## In function signatures In a signature, `'_` is exactly an elided lifetime written explicitly, so the three elision rules decide what it means: | Written | Position | Meaning | |---|---|---| | `fn len(buf: &TextBuffer<'_>) -> usize` | input | a fresh lifetime parameter | | `fn words(&self) -> SplitWhitespace<'_>` | output | the `&self` lifetime, by the receiver rule | | `fn view(src: &str) -> TextBuffer<'_>` | output | the lifetime of `src`, by the one-input rule | | `fn pick(a: &str, b: &str) -> &'_ str` | output | no rule applies: `E0106` | The last row matters: `'_` does not resolve ambiguity. It is filled by the same rules as an omitted lifetime, so when they give no answer, writing `'_` gives the same `E0106`. Only a named lifetime chooses an input. ## Why write it: hidden lifetimes in paths A return type such as `std::str::Lines` has a lifetime parameter even when you do not write it. `fn lines(&self) -> std::str::Lines` compiles, but nothing in the signature shows that the iterator borrows from `self`. Two lints exist for this: - **`mismatched_lifetime_syntaxes`**, warn-by-default since Rust 1.89, where it superseded the `elided_named_lifetimes` lint. It fires when one lifetime is written in different styles between inputs and output, such as `&self` with a bare `Lines`, and prints `warning: hiding a lifetime that's elided elsewhere is confusing` with a suggestion to write `Lines<'_>`. - **`elided_lifetimes_in_paths`**, allow-by-default and part of the `rust_2018_idioms` lint group. When enabled it flags every hidden lifetime in a path, including inputs such as `f: &mut fmt::Formatter` written without `<'_>`. ## Choosing between nothing, `'_` and a name A practical convention follows from the rules and the lints: 1. **Write nothing** for plain references such as `&str`, `&mut Vec<T>` and `&self`. The `&` already shows the borrow, and neither lint asks for more. 2. **Write `'_`** in a type path whenever the type carries a lifetime parameter: `Lines<'_>`, `fmt::Formatter<'_>`, `TextBuffer<'_>`. It marks the borrow, satisfies both lints and still lets elision choose. 3. **Write a name** when two positions must be the same lifetime, when an output must come from one particular input that elision would not pick, or when methods of an impl must refer to the impl's lifetime. Following this, a reader can tell from any signature which values are borrowed and, for outputs, from where, without opening the body. ## Where `'_` does not help - **Struct fields and type aliases**: `struct Line { text: &'_ str }` is still `E0106`; type definitions need named lifetime parameters. - **Ambiguous outputs**: as above, `'_` follows the elision rules and cannot pick an input. - **Trait-object bounds**: in `Box<dyn Trait + '_>` the placeholder follows the elision rules instead of the default object lifetime; that default is covered with trait-object lifetimes.

  • When do you need `impl<'a>` instead of `'_` in an impl header?
    Whenever the impl must name the lifetime: a method such as `fn first_line(&self) -> &'a str` that returns data from the borrowed source, or a type annotation that mentions `'a`. `'_` is anonymous and cannot be referred to, so as soon as the lifetime appears in a method signature or body, declare it with `impl<'a> TextBuffer<'a>`.
  • Does writing `-> &'_ str` fix an E0106 on a function with two reference inputs?
    No. `'_` in an output follows the same elision rules as an omitted lifetime, so with two input lifetimes and no `&self` receiver rustc still reports `error[E0106]: missing lifetime specifier`. Only a named lifetime that states which input the output borrows from resolves it.
  • What does the `elided_lifetimes_in_paths` lint add beyond `mismatched_lifetime_syntaxes`?
    `mismatched_lifetime_syntaxes` warns by default only when one lifetime is written in different styles across inputs and output, such as `&self` with a bare `Lines`. `elided_lifetimes_in_paths` is allow-by-default, enabled directly or through the `rust_2018_idioms` group, and flags every hidden lifetime in a path, including inputs such as `fmt::Formatter` written without `<'_>`.

  • '_ means the same thing as 'static.
  • Two '_ in one impl header refer to the same lifetime.
  • '_ in a return type creates a new lifetime unrelated to every input.
  • Leaving the lifetime off TextBuffer in an impl header is the same as writing '_.
  • Writing '_ lets a struct field skip declaring a lifetime parameter.

Assumes Rust 1.99; the warn-by-default mismatched_lifetime_syntaxes lint was added in Rust 1.89, superseding elided_named_lifetimes.