Lifetimes in Rust
Table of Contents
Lifetimes in Rust
What Are Lifetimes?
- Period of Validity: A lifetime represents the scope or duration for which a reference is valid. It's the region of code where the value a reference points to is guaranteed to exist in memory.
- Compile-Time Concept: Lifetimes are not a runtime feature. They are a static analysis tool used by Rust's borrow checker during compilation to enforce memory safety rules. If the borrow checker determines that a reference could outlive the data it points to, it will issue a compile-time error.
- Preventing Dangling References: The primary goal of lifetimes is to prevent "dangling references," where a reference points to memory that has already been freed.
How Lifetimes Work (The Borrow Checker)
Rust's Ownership and borrowing rules work hand-in-hand with lifetimes:
- Every Reference Has a Lifetime: Even if you don't explicitly write them, every reference in Rust has an associated lifetime.
- Borrowing Rules:
- You can have multiple immutable references (
&T) to a piece of data at a time. - You can have only one mutable reference (
&mut T) to a piece of data at a time.
- You can have multiple immutable references (
- Lifetime Elision Rules: In many common scenarios, the Rust compiler can infer lifetimes, so you don't need to write them explicitly. This is called "lifetime elision." The compiler applies a set of predefined rules to determine how input lifetimes relate to output lifetimes.
- Explicit Lifetime Annotations (
'a,'b, etc.): When the compiler cannot unambiguously infer the relationships between lifetimes (typically in functions that take references as input and return a reference), you must explicitly annotate them. These annotations are a way of telling the compiler: "The lifetime of this reference is tied to the lifetime of that reference." - Syntax: Lifetimes are denoted by an apostrophe
'followed by a name (e.g.,'a,'static). - Purpose: Lifetime annotations are descriptive, not prescriptive. You don't assign a lifetime to a reference; you describe the relationships between the lifetimes of different references to the compiler, which then checks if those relationships hold true.
Common Scenarios Requiring Explicit Lifetimes
Functions that Take References and return a Reference
When a function takes multiple references as input and returns one of them, or a reference derived from them, the compiler needs to know which input lifetime the output reference is dependent on.
- Example:
// This function takes two string slices and returns the longest one. // The returned slice's data must be valid for at least as long // as the shortest of the two input slices. fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }Here,
'ais a lifetime parameter that tells the compiler: "The reference returned by longest will have the same lifetime as the shortest of the two input referencesxandy." This ensures the returned reference won't outlive its original data.
Structs that Hold References
If a struct contains a reference, it means the struct does not own the data it points to. Therefore, the struct must ensure that the data it refers to remains valid for as long as the struct itself exists.
- Example
struct ImportantExcerpt<'a> { part: &'a str, } fn main() { let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let i = ImportantExcerpt { part: first_sentence, }; // The 'a lifetime here ensures that 'novel' lives at least as long as 'i'. // If 'novel' went out of scope before 'i', it would be a compile-time error. }The lifetime annotation 'a on
ImportantExcerptmeans that any instance ofImportantExcerptcannot outlive the reference it holds in its part field.
The 'static Lifetime
- The 'static lifetime is a special lifetime that indicates a reference is valid for the entire duration of the program.
- This applies to string literals (&'static str), global constants, and data that is intentionally "leaked" to exist indefinitely.