Lifetimes annotate how long references are valid. The compiler uses them to reject dangling references—often inferred without explicit syntax in simple code.
When explicit lifetimes appear
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
Important interview questions and answers
- Q: What problem do lifetimes solve?
A: Ensure references never outlive the data they borrow—no dangling pointers in safe Rust. - Q: Must every reference be annotated?
A: No—lifetime elision covers common patterns; explicit when the compiler cannot infer ties.
Self-check
- What does
'arepresent? - Can a function return a reference to a local variable?
Tip: Most playground code needs no explicit lifetimes—add 'a when returning references tied to parameters the compiler cannot infer.
Interview prep
- What are lifetimes for?
They tie reference validity to borrowed data so references never outlive what they point to.