lifetime

Rust Lifetime relationships, not timers

A lifetime constrains the region where a reference may be used. An annotation in a signature describes a relationship the caller must satisfy; it does not keep a value alive. Think of a borrowed label on a parcel: the label may be read only while the parcel is still available. Expected output (not executed): A12 Kept: A12 Why: The inner reference is used while the owning string remains valid. Ending the inner block does not destroy the outer string. Common mistake: Treating a lifetime as a runtime countdown or equating a borrow with the entire scope of a variable.

Formal Syntax & Structure

rust syntaxrust
&'a T

Working Example

Example Snippetrust
fn main() {    let parcel = String::from("A12");    {        let label = &parcel;        println!("{label}");    }    println!("Kept: {parcel}");}
Rust Reference