Sub topic 1
Rust Lifetimes: How the Borrow Checker Tracks How Long References Are Valid
Prerequisites
This chapter assumes you know Rust functions, ownership, moves, String, &str, and the rules for shared and mutable references.
Quick review: references and borrowing
A reference gives access to a value without taking ownership. &T is a shared reference, so several parts of a program may read the value. &mut T is a mutable reference, and it must be the only active reference while it is used.
fn main() {
let mut message = String::from("hello");
let length = message.len(); // shared borrow ends after this statement
message.push_str(" world"); // mutable borrow is now allowed
println!("{message} ({length} characters initially)");
}Why lifetimes exist: preventing dangling references
A lifetime is the span during which a reference can safely be used. Rust rejects a dangling reference, which points to data that has already been dropped.
fn main() {
let text = {
let value = String::from("temporary");
value
}; // value is moved out, so text owns valid data
println!("{text}");
}The compiler checks that every reference is used only while its target remains alive. A reference to a local value cannot escape the scope that owns that value.
How the borrow checker sees scopes, and non-lexical lifetimes
The borrow checker proves that borrowing rules hold. A scope is a region where a value is valid. With non-lexical lifetimes, a borrow usually ends at its last use, rather than automatically lasting to the end of its enclosing block.
This lets Rust accept code such as reading a string's length and then mutating the string. The immutable borrow ends when len finishes using it.
> callout note > A lifetime describes validity. It does not keep a value alive and does not automatically make a reference last longer.
Reading and writing lifetime annotations
A lifetime parameter starts with an apostrophe, such as 'a. It names a relationship between references. It does not name a fixed number of seconds.
Lifetimes in function signatures
When a function returns a reference, its signature must show how that reference relates to its inputs:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let first = String::from("long");
let second = String::from("longer");
println!("{}", longest(&first, &second));
}This says the returned reference is valid for the shared portion of x and y's lifetimes. The annotation guides the compiler; it does not choose which input lives longer.
Exercise
Does adding 'a make a borrowed local value live longer?
Show answer
No. It describes a required relationship, and the compiler still rejects any reference used after its value is dropped.