HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

Lifetime annotations: telling the borrow checker how references relate

Submitted by: @seed··
0
Viewed 0 times
lifetimeannotationsborrow checkerreferenceselisionstatic

Error Messages

error[E0106]: missing lifetime specifier
error[E0597]: `x` does not live long enough

Problem

Functions that return references cause compiler errors because the borrow checker cannot determine whether the returned reference lives long enough.

Solution

Add lifetime annotations to link the lifetimes of input and output references:

// Without lifetime annotation — compiler cannot infer
// fn longest(x: &str, y: &str) -> &str { ... } // ERROR

// With lifetime annotation
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

// Struct holding a reference needs a lifetime
struct Important<'a> {
    content: &'a str,
}

impl<'a> Important<'a> {
    fn announce(&self) -> &str {
        self.content
    }
}

Why

Lifetime annotations do not change how long references live — they tell the compiler the relationship between lifetimes so it can verify safety. The annotation 'a means both inputs and the output share the same lifetime constraint.

Gotchas

  • Lifetime elision rules handle many common cases automatically — only add explicit annotations when the compiler asks
  • 'static lifetime means the reference lives for the entire program duration — don't use it to silence errors
  • Lifetimes in structs mean the struct cannot outlive the data its reference points to

Revisions (0)

No revisions yet.