Introduction to Lifetimes
In this page:
What a Lifetime Represents
A lifetime is the compiler's internal tracking of how long a particular reference remains valid, ensuring it never outlives the data it points to.
Example: What a Lifetime Represents
fn main() {
let text = String::from("valid data");
let reference = &text;
println!("{}", reference);
}
Login to try C/C++/Java/PHP code in the editor
Most Lifetimes Are Inferred
In the vast majority of code, the compiler infers lifetime relationships automatically without you writing any lifetime syntax at all.
Example: Most Lifetimes Are Inferred
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
fn main() {
let sentence = String::from("hello world");
println!("{}", first_word(&sentence));
}
Login to try C/C++/Java/PHP code in the editor
Lifetimes Prevent Dangling References
The entire purpose of lifetime tracking is to guarantee a reference can never be used after the data it points to has been freed, catching the mistake at compile time instead of causing a crash later.
Example: Lifetimes Prevent Dangling References
fn longest_of_two<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let a = String::from("short");
let b = String::from("much longer string");
println!("{}", longest_of_two(&a, &b));
}
Login to try C/C++/Java/PHP code in the editor
No Runtime Cost
Lifetime checking happens entirely during compilation. Once the code compiles successfully, no lifetime information remains in the compiled binary, and there is zero runtime overhead.
Example: No Runtime Cost
fn main() {
let value = 100;
let borrowed = &value;
println!("Borrowed with zero runtime cost: {}", borrowed);
}
Login to try C/C++/Java/PHP code in the editor
- Assuming lifetimes control how long data lives -- they only describe relationships that already exist, they don't extend anything.
- Thinking every reference needs an explicit lifetime annotation -- most cases are inferred automatically without one.
- Believing lifetimes are a runtime feature -- they are purely a compile-time concept with zero runtime cost.
- A lifetime describes how long a reference remains valid relative to the data it points to.
- Most lifetimes are inferred automatically by the compiler and never need to be written explicitly.
- Lifetimes exist to prevent dangling references, entirely at compile time.
- Explicit lifetime annotations become necessary when the compiler cannot infer the relationship on its own.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: