1. What Are Lifetimes?
A lifetime describes how long a reference is valid.
In Rust, every reference has a lifetime. Rust checks that the referenced data remains valid for as long as the reference is used.
Consider this example:
This code is valid because name remains alive while reference is being used.
Why Are Lifetimes Important?
Lifetimes prevent problems such as:
- Dangling references
- Accessing data after it has been destroyed
- Returning references to local variables that no longer exist
Rust checks these situations at compile time.
2. Understanding a Dangling Reference
A dangling reference is a reference that points to data that is no longer valid.
Consider this example:
This code produces a compiler error.
Why?
nameis created inside the inner block.referenceborrowsname.- The inner block finishes.
nameis destroyed.- The program tries to use
reference.
Rust prevents this because the reference would outlive the data it points to.
3. Understanding Lifetime Annotations
Sometimes Rust cannot determine the relationship between references automatically.
In such cases, we can use lifetime annotations.
Lifetime annotations describe relationships between references. They do not extend the actual lifetime of data.
Rust lifetime names usually start with an apostrophe.
Example:
The most commonly used annotation is:
Here, 'a is a lifetime parameter.
It does not represent a fixed amount of time. It represents a relationship between lifetimes.
4. Lifetime Annotation in Functions
Consider a function that accepts two string references and returns one of them.
Output:
Explanation:
<'a>declares a lifetime parameter.x: &'a strmeansxis a string reference with lifetime'a.y: &'a strmeansyhas the same declared lifetime.-> &'a strmeans the returned reference is associated with that lifetime.
This annotation tells Rust that the returned reference cannot be used beyond the lifetime shared by the input references.
It does not mean that both references must have exactly the same actual lifetime. Rust can choose a shorter common lifetime.
5. Why Do We Need Lifetimes in Functions?
Consider this function:
Rust cannot determine the relationship between the input references and the returned reference from this signature alone.
The compiler will report a missing lifetime specification.
We can fix it by adding a lifetime annotation:
Now Rust knows the relationship between the references.
6. Lifetime Annotations with Structs
A struct can also store references.
When a struct contains references, it may need lifetime annotations.
Example:
Output:
Explanation:
The lifetime 'a tells Rust that the reference stored in Student must remain valid for the relevant lifetime of the struct.
The struct does not own the name. It borrows it.
7. Multiple Lifetime Parameters
Sometimes a function or struct needs more than one lifetime parameter.
Example:
Output:
Here:
'arepresents the lifetime of the first reference.'brepresents the lifetime of the second reference.
The two references do not need to have the same lifetime.
8. Lifetime Annotations with Methods
You can also use lifetime annotations in methods.
Example:
Output:
The returned reference is tied to the borrow of self through lifetime elision rules.
9. The Static Lifetime ('static)
Rust provides a special lifetime called 'static.
A reference with the 'static lifetime can remain valid for the entire duration of the program.
Example:
Output:
String literals have the 'static lifetime because they are stored in the program's binary.
Another example:
Output:
Important: Do not use 'static simply to fix lifetime errors. It means the reference must genuinely be valid for the entire program.
10. Lifetime Elision Rules
Rust can automatically determine lifetimes in many situations.
This is called lifetime elision.
For example:
You do not need to write:
Both signatures have the same meaning.
Rust applies lifetime elision rules to determine the relationship.
The Three Lifetime Elision Rules
- Each reference parameter gets its own lifetime parameter.
- If there is exactly one input lifetime, that lifetime is assigned to all output references.
- If one of the input parameters is
&selfor&mut self, the lifetime ofselfis assigned to output references.
These rules allow many functions to be written without explicit lifetime annotations.
11. Lifetime Bounds
A lifetime bound can specify that one lifetime must outlive another.
The syntax uses the : symbol.
Example:
Here:
means that lifetime 'a must last at least as long as lifetime 'b.
12. Static Lifetime Bound with Generics
You can combine lifetimes with generic type parameters and trait bounds.
Example:
Here, T: 'static means that the type does not contain non-static borrowed references.
It does not mean that the value itself must live forever.
For example, an owned String can be dropped normally even though String satisfies the 'static bound.
13. Difference Between Ownership, Borrowing, and Lifetimes
Concept | Purpose |
|---|---|
Ownership | Determines who owns a value |
Borrowing | Allows references to access a value |
Lifetimes | Ensure references remain valid while used |
Example:
nameowns the String.referenceborrows the String.- Rust checks that
nameremains valid whilereferenceis used.
14. Common Mistakes
Mistake | Explanation |
|---|---|
Returning a reference to a local variable | The local variable is destroyed when the function ends |
Thinking | It represents a lifetime relationship |
Adding | It does not solve ordinary lifetime problems |
Forgetting lifetime parameters in reference-holding structs | The struct may need to specify how long its references remain valid |
Confusing borrowing with ownership | A reference does not become the owner of the data |