bhylu.com

Advertisements

Rust Lifetimes

Express a reference relationship without extending an owner’s life.

How it works

Lifetime annotations describe relationships between references so the compiler can check valid uses. They do not keep a local value alive after its owner is dropped. Many simple functions use elided lifetimes automatically. When several input references could supply an output, an explicit relationship can make the contract unambiguous and constrain callers appropriately.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

lifetimes.rs

fn main() {
    fn longer<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b } }
    let first = String::from("north");
    let second = String::from("west");
    let chosen = longer(&first, &second);
    assert_eq!(chosen, "north");
    println!("Borrowed choice: {chosen}");
}

Expected result

Borrowed choice: north

Both owned strings remain alive while the chosen reference is used. The signature ties the result to the common valid borrowing region of the inputs. A caller cannot use that annotation to return a reference into an already dropped local String. The example compares byte lengths, which is a deliberate simple text policy.

Primary technical reference: Rust documentation.