Code Example Template
Deep-Dive System Documentation
Lifetimes: Reference Validity
A lifetime is a parameter the Rust compiler uses to track how long a reference points to valid memory. Most lifetimes are inferred automatically via Lifetime Elision Rules, but when structs or functions store references, they must be declared explicitly.
Dangling Pointer Prevention
Consider a structure storing an application macro name reference:
struct LauncherItem<'a> {
label: &'a str, // 'a guarantees that label does not outlive its source memory
}
The 'a annotation acts as a compile-time contract. If the underlying string buffer backing label is dropped or freed, but the LauncherItem is still accessed, the compiler blocks compilation immediately.
Static Lifetimes ('static)
The special 'static lifetime means the reference remains valid for the entire duration of the running program (e.g., string literals compiled into the executable binary).
let global_shortcut: &'static str = "Alt+Space";
Quick Reference Guide
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { x }