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
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
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
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 itAnnotations 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:
// You write:fn first_word(s: &str) -> &str { ... }
// Compiler infers:fn first_word<'a>(s: &'a str) -> &'a str { ... }The elision rules:
- Every reference parameter gets its own lifetime
- If there's exactly one input lifetime, every output borrows it
- If one parameter is
&selfor&mut self, its lifetime flows to the outputs
Lifetimes in Structs
Structs that hold references need lifetime annotations:
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_sentenceHere are both pieces in one program. Run it, then break it on purpose.
The 'static Lifetime
'static means the reference lives for the entire program:
let s: &'static str = "I live forever"; // string literals are 'staticDon'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.