By the end of this lesson
Read a lifetime annotation as a relationship between borrows.
Before you start
- Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
- Complete lesson 22, or be comfortable explaining and running its examples.
Three words to know
- Lifetime
- The validity region of a reference.
- Annotation
- A declared relationship, not an instruction to keep data alive.
- Dangling reference
- A reference to data that is no longer valid.
1. Understand the idea
Lifetime annotations tell the compiler how borrowed inputs and outputs relate. They do not extend a local value’s life and cannot make a reference to dropped data safe. Many simple functions use elision, where Rust infers the relationship. When there are multiple borrowed inputs, an explicit annotation can state that the returned reference must be usable only while the relevant inputs remain valid.
2. Save, run and observe
Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.
fn longer<'a>(left: &'a str, right: &'a str) -> &'a str {
if left.len() >= right.len() { left } else { right }
}
fn main() {
let left = String::from("Rust");
let right = String::from("Cargo");
println!("{}", longer(&left, &right));
}
What you should see · example output
Cargo
rustc --edition=2024 lesson.rs -o lesson
./lesson3. Explain the result
The result refers to one of the original strings. Both are still owned by main while the reference is printed. The annotation does not allocate or clone either input. This example compares byte lengths deliberately. Do not add 'static as a general workaround for a lifetime error.
YOUR TURN
A small check before you continue
Would an annotation allow returning &str pointing into a String created only inside longer?
Show a suggested answer
No. That String would be dropped on return. Return an owned String or borrow data owned by the caller.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
