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
| Concept | What it means |
|---|---|
| Lifetime | How long a reference stays valid. Every reference has one. |
| 'a | The syntax for a lifetime annotation. An apostrophe followed by a letter. |
| Dangling reference | A reference that points to data that has already been dropped. Rust refuses to compile this. |
| Borrow checker | The part of the Rust compiler that checks every reference is valid for as long as it is used. |
| Lifetime annotation | A label you add to a function signature to tell the compiler how the lifetimes of its references relate to each other. |
| Lifetime elision | Rules that let the compiler infer lifetimes automatically so you do not have to write them. |
| 'static | A special lifetime meaning the reference lives for the entire program. String literals have this lifetime. |
| Term | What it means | When you use it |
|---|---|---|
| Lifetime | How long a reference is valid before Rust frees the data it points to. | Every time you write a reference in Rust. Often inferred automatically. |
| 'a | The 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 reference | A 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 checker | The part of the compiler that tracks reference lifetimes and rejects invalid code. | Always active. It runs automatically every time you compile Rust code. |
| Lifetime annotation | A 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 elision | Built-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. |
| 'static | A lifetime that lasts for the entire program. The reference is always valid. | String literals and constants defined at compile time. |