Topic
Lifetimes
A lifetime tells Rust how long a reference stays valid. Learn how to annotate lifetimes and when Rust figures them out for you.
Quick Reference
ConceptWhat it means
LifetimeHow long a reference stays valid. Every reference has one.
'aThe syntax for a lifetime annotation. An apostrophe followed by a letter.
Dangling referenceA reference that points to data that has already been dropped. Rust refuses to compile this.
Borrow checkerThe part of the Rust compiler that checks every reference is valid for as long as it is used.
Lifetime annotationA label you add to a function signature to tell the compiler how the lifetimes of its references relate to each other.
Lifetime elisionRules that let the compiler infer lifetimes automatically so you do not have to write them.
'staticA special lifetime meaning the reference lives for the entire program. String literals have this lifetime.
TermWhat it meansWhen you use it
LifetimeHow long a reference is valid before Rust frees the data it points to.Every time you write a reference in Rust. Often inferred automatically.
'aThe syntax for naming a lifetime. An apostrophe followed by a letter.When a function returns a reference and the compiler needs to know which input it came from.
Dangling referenceA reference that points to freed memory. The borrow checker makes this impossible to compile.Something Rust prevents at compile time so you never see it at runtime.
Borrow checkerThe part of the compiler that tracks reference lifetimes and rejects invalid code.Always active. It runs automatically every time you compile Rust code.
Lifetime annotationA label on a function signature that describes how input and output lifetimes relate to each other.When the compiler cannot infer the relationship on its own, usually when multiple references are involved.
Lifetime elisionBuilt-in rules that let the compiler infer lifetimes in the most common cases.One-reference-in, one-reference-out functions benefit from this automatically. You write no annotation at all.
'staticA lifetime that lasts for the entire program. The reference is always valid.String literals and constants defined at compile time.