Skip to main content
Be Bitwise
RustBorrowing & Lifetimes

Lifetime Annotations

Lifetimes are how Rust tracks how long references stay valid. The compiler infers them most of the time. When it can't, you spell them out.

The Problem

rust
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}

Won't compile. The compiler can't tell whether the returned reference points into x or y, so it has no idea how long the result is good for.

Lifetime Annotations

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

'a is a lifetime parameter. Translation: "the returned reference is good for as long as both x and y are." The compiler enforces that contract at every call site.

How It Works

rust
let string1 = String::from("long string");
let result;
{
let string2 = String::from("xyz");
result = longest(&string1, &string2);
println!("{}", result); // OK: both strings are alive
}
// println!("{}", result); // ERROR: string2 is dropped, result might reference it
Key Concept

Annotations don't change how long values live. They describe relationships between references for the compiler's benefit. With that information in hand, it can stop a dangling reference before it ever happens.

Lifetime Elision

The compiler infers lifetimes in common patterns:

rust
// You write:
fn first_word(s: &str) -> &str { ... }
// Compiler infers:
fn first_word<'a>(s: &'a str) -> &'a str { ... }

The elision rules:

  1. Every reference parameter gets its own lifetime
  2. If there's exactly one input lifetime, every output borrows it
  3. If one parameter is &self or &mut self, its lifetime flows to the outputs

Lifetimes in Structs

Structs that hold references need lifetime annotations:

rust
struct Excerpt<'a> {
text: &'a str,
}
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence;
{
let i = novel.find('.').unwrap_or(novel.len());
first_sentence = Excerpt { text: &novel[..i] };
}
println!("{}", first_sentence.text); // OK: novel outlives first_sentence

Here are both pieces in one program. Run it, then break it on purpose.

Try itUncomment the outside println! to get E0597, then put it back and delete the <'a> annotations from longest to get E0106.
Rust (1.40.0)

The 'static Lifetime

'static means the reference lives for the entire program:

rust
let s: &'static str = "I live forever"; // string literals are 'static

Don't reach for 'static to silence lifetime errors. Nine times out of ten, it's the design that needs rethinking.

Challenges

Write a function that returns the first word of a string as a slice.

Rust (1.40.0)