Deepen your understanding of Rust's lifetime system — lifetime annotation syntax, the three elision rules, the 'static lifetime, how NLL improved the borrow checker, and lifetime subtyping constraints.
0 / 5 completed
1 / 5
What do lifetime annotations like 'a tell the Rust compiler?
Lifetime annotations do not change how long data lives; they describe relationships. In fn longest<'a>(x: &'a str, y: &'a str) -> &'a str, 'a tells the compiler the returned reference lives no longer than the shorter of x or y, enabling the borrow checker to reject dangling references.
2 / 5
What are Rust's lifetime elision rules?
Lifetime elision lets the compiler infer lifetimes in many common function signatures without explicit annotations. The three rules cover: (1) each input reference gets its own lifetime; (2) if there is exactly one input lifetime, it is assigned to all output lifetimes; (3) if one of the inputs is &self/&mut self, its lifetime is assigned to all outputs.
3 / 5
What does the 'static lifetime mean in Rust?
The 'static lifetime means the reference is valid for the entire program run. String literals (&'static str) are embedded in the binary. T: 'static as a bound means T contains no non-static references — it does not require T to live forever, just that it could if needed.
4 / 5
What problem did Non-Lexical Lifetimes (NLL) solve in Rust?
NLL (stabilised in Rust 2018) made the borrow checker region-based rather than scope-based. Before NLL, a borrow lasted until the closing brace of its scope even if the reference was last used earlier. NLL ends the borrow at the final use, eliminating many previously necessary code restructurings.
5 / 5
What does lifetime subtyping express with a bound like 'b: 'a?
Lifetime subtyping'b: 'a reads as "'b outlives 'a". It is used when a struct or function needs to store or return a reference with one lifetime into a context that expects a shorter lifetime. The longer lifetime is a subtype of the shorter because it satisfies all the same constraints and more.