Lifetime ('a)
A lifetime ensures that a "borrowed" reference doesn't outlive the
actual data it is pointing to
If the original data gets destroyed, but your reference tries to stick
around, it becomes a dangerous "dangling reference". Rust stops this
from happening at compile time
Lifetimes are checked using Borrow checker.
'a is a Lifetime. it describes
how long a reference is valid.
A lifetime in Rust is the duration during which a
reference is valid
Lifetime annotations look like <'a>, 'a, etc. — they're just
labels for the compiler
| Does not compile | Compile (With Lifetime Annotation) |
|---|---|
|
Lifetime? Prefix every parameter with 'a. Apostrophe ('a), denotes reference has generic lifetime.
How this worked? This says: "Both x and y live at least as long as returned lifetime 'a" The returned reference will live at least as long as the shortest of the 2 input references |
Lifetime types
1. Implicit (Elided) Lifetimes
Most lifetimes are automatically inferred by the compiler. You don't write them — they're "elided."
fn print_string(s: &str) {
println!("{}", s);
}
let text = "Hello";
print_string(text); // No lifetime annotation needed!
// The compiler infers that the return type (nothing here) doesn't
// depend on the input lifetime. When a function only takes references
// but doesn't return them, lifetimes are elided.
2. Explicit (Named) Lifetimes
We write these when the compiler can't infer which lifetime a reference ties to — typically when returning a reference from multiple input references. Example above
3. 'static Lifetime
This is a special lifetime that means the reference lives for the entire duration of the program — typically for string literals or data stored in the binary.
fn GetName() -> &'static str {
"This is a David" // Lives forever!
}
let s = GetName();
println!("{}", s); // Always safe
Lifetime in struct
Why we need lifetime in struct? if we want to store reference in struct, ie struct does not hold Owned types.
| Will not compile | Compiles (With Lifetime) |
|---|---|
|
|