Rust Tutorial: Lifetimes
Lifetime annotations, the borrow checker, and why Rust needs lifetime parameters.
Lifetimes
Every reference in Rust has a lifetime — the scope during which it is valid.
Usually Rust infers lifetimes automatically. You only need to annotate when the compiler cannot figure out the relationship between multiple references.
What you'll learn in this Rust lifetimes tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 22 minutes.
- Why lifetimes exist — This code would cause a dangling reference — a reference to freed data.
- Simple lifetime annotation — When a function returns a reference derived from its inputs, Rust needs to know which input it comes from.
- Lifetime elision rules — Rust has three lifetime elision rules to avoid annotation boilerplate.
- Structs with lifetime annotations — If a struct holds a reference, it needs a lifetime parameter.
- Multiple lifetime parameters — Sometimes inputs have different lifetimes.
- Static lifetime — `'static` means the reference lives for the entire program duration.
- Lifetime bounds on generics — Generic types can have lifetime constraints too.
- Lifetime summary — Lifetimes ensure references never outlive the data they point to.
Rust Lifetimes concepts covered
- Lifetimes