Lifetime (Rust)
A lifetime is how long a reference is valid. The compiler usually infers it, but sometimes you annotate explicitly to describe the relationships between references.
Why annotate?
Annotations don’t change how long references actually live. They let the borrow checker reason about functions using only local information (signatures), without looking at every call site.
Analogy: “I’ll only buy eggs with at least two weeks until expiry.” The rule doesn’t change the eggs, it describes what’s acceptable.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}All parameters and the return share lifetime 'a, so the returned reference lives at least as long as the shorter of the two inputs.
'static grants immortality: memory that could live for the whole program (string literals do). Used in the thread::spawn signature because threads are estimated to be immortal.
Don't paper over errors with
'staticThe compiler may suggest
'staticwhen the real fix is to move/copy the data or wrap it in an Arc. Applying'staticjust pushes the error up the call chain until you’re stuck. Memory kept alive forever that’s no longer useful is essentially a leak.