Rust Lifetimes
Every reference in Rust has a lifetime: the span of code during which the reference is valid. Most of the time lifetimes are inferred and you never write them. But when a function takes several references and returns one, the compiler sometimes needs a hint about how they are related. Lifetime annotations provide that hint.
Note: Lifetime annotations never change how long a value lives. They only describe relationships between references so the compiler can check them.
The problem lifetimes solve
The borrow checker's job is to make sure no reference outlives the data it points to. Here is the classic mistake it catches:
fn main() {
let r;
{
let short_lived = 5;
r = &short_lived;
} // short_lived is dropped here
println!("{}", r); // r would point to freed memory
}error[E0597]: `short_lived` does not live long enough
--> src/main.rs:5:13
|
4 | let short_lived = 5;
| ----------- binding `short_lived` declared here
5 | r = &short_lived;
| ^^^^^^^^^^^^ borrowed value does not live long enough
6 | } // short_lived is dropped here
| - `short_lived` dropped here while still borrowed
7 | println!("{}", r); // r would point to freed memory
| - borrow later used hereWithin one function the compiler can see everything. Across function boundaries it relies on the function signature — and that is where annotations come in.
Lifetime annotation syntax
A lifetime parameter starts with an apostrophe and is usually short: 'a, 'b. It is declared in angle brackets after the function name, like a generic type, and then attached to references:
| Written | Meaning |
|---|---|
&i32 |
a reference (lifetime inferred) |
&'a i32 |
a reference that lives at least as long as 'a |
&'a mut i32 |
a mutable reference with lifetime 'a |
&'static str |
a reference valid for the entire program |
A function that needs annotations
This function returns whichever of two strings is longer. The compiler can't know whether the result borrows from a or b, so we tell it: "the result lives as long as both inputs".
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let city1 = String::from("Copenhagen");
let city2 = String::from("Oslo");
let result = longer(&city1, &city2);
println!("Longer name: {}", result);
}Longer name: Copenhagen
'a becomes the shorter of the two input lifetimes, and the returned reference may only be used while both inputs are still alive. Without <'a> you would get "missing lifetime specifier".
Here is what the annotation protects you from:
fn main() {
let outer = String::from("long string");
let result;
{
let inner = String::from("xyz");
result = longer(&outer, &inner);
} // inner dropped here
println!("{}", result); // error: `inner` does not live long enough
}Lifetime elision: when you don't need to write them
Writing 'a everywhere would be noisy, so the compiler applies elision rules:
- Each reference parameter gets its own lifetime.
- If there is exactly one input reference, the output gets that same lifetime.
- If one of the parameters is
&selfor&mut self, the output gets the lifetime ofself.
That's why this function needs no annotations — there's only one input reference:
fn initials(name: &str) -> &str {
let end = name.find(' ').unwrap_or(name.len());
&name[..1.min(end)]
}
fn shortest_word(text: &str) -> &str {
let mut best = text;
for word in text.split_whitespace() {
if word.len() < best.len() {
best = word;
}
}
best
}
fn main() {
println!("{}", initials("Grace Hopper"));
println!("{}", shortest_word("lifetimes are not so scary"));
}G
so
Lifetimes in structs
A struct that holds a reference must declare a lifetime, which promises that the struct cannot outlive the data it borrows.
struct Highlight<'a> {
text: &'a str,
page: u32,
}
impl<'a> Highlight<'a> {
fn describe(&self) -> String {
format!("p.{}: \"{}\"", self.page, self.text)
}
fn first_word(&self) -> &str {
self.text.split(' ').next().unwrap_or("")
}
}
fn main() {
let book = String::from("Ownership is Rust's most unique feature. It enables safety.");
let first_sentence = book.split(". ").next().unwrap();
let h = Highlight { text: first_sentence, page: 59 };
println!("{}", h.describe());
println!("Starts with: {}", h.first_word());
}p.59: "Ownership is Rust's most unique feature"
Starts with: Ownership
Highlight borrows from book, so book must stay alive as long as h is used. first_word needs no annotation thanks to elision rule 3.
The 'static lifetime
'static means "valid for the whole program". All string literals have type &'static str because they're stored in the program binary.
const GREETING: &'static str = "Hello from the binary!";
fn level_name(level: u8) -> &'static str {
match level {
0 => "beginner",
1 => "intermediate",
_ => "expert",
}
}
fn main() {
println!("{}", GREETING);
for lvl in 0..3 {
println!("level {} = {}", lvl, level_name(lvl));
}
}Hello from the binary!
level 0 = beginner
level 1 = intermediate
level 2 = expert
Tip: If the compiler suggests adding
'staticto fix an error, think twice. Often the real fix is to return an owned value (String) instead of a reference.
Test yourself
What do lifetime annotations like 'a do?
- Make values live longer
- Describe how the lifetimes of references relate, so the compiler can check them
- Free memory early
- Make references mutable
Why does fn first(s: &str) -> &str need no lifetime annotation?
&strnever needs lifetimes- Elision: with exactly one input reference, the output gets its lifetime
- The function is too short
- It returns a
'staticvalue
What is the type of the literal "hi"?
String&'static str&'a Stringchar