Rust Tutorial · Ownership and Borrowing · Lesson 12 of 29
Rust Lifetimes
What lifetime annotations mean, when the compiler needs them, and how they prevent dangling references.
Why lifetimes exist
A reference must never outlive the value it points to. Usually the compiler works this out itself; when a
function returns a reference derived from several inputs, you tell it how they relate with a lifetime
parameter such as 'a:
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let first = String::from("borrow checker");
let result;
{
let second = String::from("rust");
result = longer(&first, &second);
println!("longer: {result}");
}
// println!("{result}"); // error: `second` does not live long enough
}
Output
longer: borrow checker
Run this on your computer — see “Get Started” for setup.
<'a> says: the returned reference lives as long as both inputs do. Lifetimes don't change how long values
live; they describe relationships the compiler then checks.
Structs holding references
A struct that stores a reference needs a lifetime too:
struct Excerpt<'a> {
text: &'a str,
}
impl<'a> Excerpt<'a> {
fn first_sentence(&self) -> &'a str {
self.text.split('.').next().unwrap_or(self.text)
}
}
fn main() {
let article = String::from("Rust is fast. It is also safe.");
let excerpt = Excerpt { text: &article };
println!("{}", excerpt.first_sentence());
}
Output
Rust is fast
Run this on your computer — see “Get Started” for setup.
If lifetimes get complicated, owning the data (String instead of &str) is often the simpler design.
Test yourself
Do lifetime annotations change how long a value lives?
Yes, they extend itNo, they describe relationships the compiler checksYes, they make it staticOnly in unsafe code
Show answer
Answer: No, they describe relationships the compiler checks