liveBook · Manning

Anonymous lifetime

As explained in Learn Rust in a Month of Lunches

An anonymous lifetime is Rust's inferred lifetime notation, written as `'_'`, for a reference whose specific lifetime name does not need to be written.

Rust writes an anonymous lifetime as `'_`. It marks a reference whose specific lifetime name does not need to be written. When a struct already declares its lifetime, use this shorthand in an `impl` block. section 10.2.3

Following the compiler’s suggestion

For `struct Adventurer<'a> { name: &'a str, hit_points: u32 }`, `impl Adventurer` produces an implicit-elision error. Change it to `impl Adventurer<'_>`; the anonymous lifetime tells Rust that the implementation uses the struct’s reference lifetime without naming it. section 10.2.3

struct Adventurer<'a> {
    name: &'a str,
    hit_points: u32,
}
 
impl Adventurer<'_> {
    fn take_damage(&mut self) {
        self.hit_points -= 20;
        println!("{} has {} hit points left!", self.name, self.hit_points);
    }
}

See the corrected implementation using `Adventurer<'_>`. section 10.2.3

The same shorthand can connect lifetime parameters on traits and structs, while named lifetimes remain useful when their relationships must be stated explicitly. section 10.2.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines the shorthand and demonstrates compiler-guided correction, but stops short of detailed lifetime semantics.
Examples
Uses `Adventurer`, `Display`, compiler errors, and trait implementations with one or multiple lifetime parameters.
What you can do after
Diagnose/debug with it by replacing an omitted struct lifetime with `<'_>` in an implementation.
How it connects
Connects anonymous lifetimes to references, structs, impl blocks, traits, and named lifetimes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.