Concept Flow - Why lifetimes exist
Start: Reference created
Check: Reference valid?
Use reference
End
This flow shows how Rust checks if a reference is valid during compilation using lifetimes to prevent errors.
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{}", r);
}| Step | Action | Variable States | Lifetime Check | Result |
|---|---|---|---|---|
| 1 | Declare r (reference) | r: uninitialized | N/A | OK |
| 2 | Enter inner scope | x: uninitialized | N/A | OK |
| 3 | Initialize x = 5 | x: 5 | N/A | OK |
| 4 | Assign r = &x | r: &x (points to 5) | r lifetime <= x lifetime? | OK |
| 5 | Exit inner scope | x: dropped | r now dangling? | Error: r points to invalid memory |
| 6 | Attempt println!("{}", r) | r: dangling reference | Compile error | Program does not compile |
| Variable | Start | After Step 3 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|
| x | uninitialized | 5 | 5 | dropped | dropped |
| r | uninitialized | uninitialized | &x (valid) | &x (dangling) | dangling |
Rust lifetimes track how long references are valid. They prevent dangling references by ensuring references don't outlive data. Compiler checks lifetimes at compile time. If a reference lives longer than the data it points to, compilation fails. Lifetimes help keep programs safe and bug-free.