Lifetimes Explained
A lifetime is the span during which a reference is valid. Lifetime parameters like 'a relate references in function signatures and structs so the compiler can reject dangling pointers.
Search across all documentation pages
A lifetime is the span during which a reference is valid. Lifetime parameters like 'a relate references in function signatures and structs so the compiler can reject dangling pointers.
fn first<'a>(items: &'a [i32]) -> Option<&'a i32> {
items.first()
}
fn main() {
let data = vec![3, 1, 4];
println!("{:?}", first(&data));
}When to reach for this: Returning references from functions, storing references in structs, or understanding "does not live long enough" errors.
struct Excerpt<'a> {
text: &'a str,
}
fn excerpt<'a>(full: &'a str, end: usize) -> Excerpt<'a> {
Excerpt { text: &full[..end.min(full.len())] }
}
fn main() {
let article = String::from("Rust lifetimes are compile-time checks.");
let e = excerpt(&article, 4);
println!("{}", e.text);
}What this demonstrates:
Excerpt<'a> cannot outlive the String it borrowsfull input'a means "valid for some region at least as long as 'a"Without lifetimes, this would compile unsafely:
// impossible in safe Rust
// fn dangle() -> &str { let s = String::from("x"); &s }'static is the longest lifetime (entire program)if with different locals - Unified lifetime may fail. Fix: Return owned value or ensure both arms borrow same source.Pin, or owned graph (Rc).'static with immortality - Means valid for program duration, not that data never frees if leaked differently. Fix: Read 'static page.| Alternative | Use When | Don't Use When |
|---|---|---|
Owned String | Independent result needed | Zero-copy view required |
Cow<'a, str> | Maybe borrow, maybe own | Always one strategy |
| Indices into parent buffer | Stable handles | Simple one-off substring |
Arc<str> | Shared immutable text | Single owner suffices |
No. They are compile-time labels for borrow validity, not runtime memory management.
Yes, in many local and function cases via elision rules.
A lifetime parameter name. Convention starts at 'a, 'b. Could be 'line for clarity.
Only those storing references. Owned fields need no lifetime params.
Yes - that is the borrow checker's job to catch when a ref would dangle.
Quantifies over any lifetime - used with trait objects and some fn traits.
Self-referential futures use Pin internally; do not hand-roll without understanding.
Scopes often align with lifetimes but NLL ends loans before scope end sometimes.
No. They do not exist at runtime.
Lifetime Annotations for writing bounds explicitly.
'a'static & Bounds - 'static meaningStack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 16, 2026