Sub topic 1
Rust Advanced Lifetimes: Variance and Higher-Ranked Trait Bounds
Prerequisites.
This chapter assumes ownership, borrowing, references, basic lifetime annotations, generics, trait bounds, and the Fn traits.
Lifetimes and outlives bounds: a quick refresher
A lifetime describes how long a reference is valid. The compiler checks that every reference is used only while its referent is alive.
The bound 'long: 'short means that 'long outlives 'short. It does not mean the two lifetimes have equal lengths. It means every use valid for 'short is also within 'long.
Lifetime subtyping: when a longer lifetime can stand in for a shorter one
Rust can treat a reference with a longer lifetime as a reference with a shorter lifetime. This is lifetime subtyping. The compiler shortens the usable part of the reference; it does not change the object’s actual lifetime.
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let outer = String::from("lives longer");
{
let inner = String::from("short");
let result = longest(&outer, &inner);
println!("{result}");
}
}Here, the borrow of outer is shortened to the inner block’s lifetime so both arguments satisfy 'a.
What variance means
Variance describes how a type changes when one of its parameters changes.
| Kind | Relationship |
|---|---|
| Covariant | A longer lifetime can become a shorter lifetime |
| Contravariant | The relationship reverses |
| Invariant | The lifetime must remain exactly as specified |
Covariance: shrinking lifetimes through `&` and containers
Shared references, written &'a T, are covariant in 'a. Many owning containers are also covariant when their contents are covariant. For example, Vec<&'long str> can generally be used where Vec<&'short str> is required when 'long: 'short.
Covariance is safe because a shared reference only permits reading. Shortening its valid use cannot expose invalid data.
>callout note Think of covariance as safely shrinking the promise made by a type. >```
Invariance: why `&mut T` and `Cell<T>` cannot shrink
Mutable references are invariant in their pointed-to type. &mut T both reads and writes T. If the compiler allowed arbitrary shrinking, code could write a short-lived reference into a place that promises a longer-lived reference.
Cell<T> has the same issue through interior mutability: it can replace its stored value even when accessed through a shared reference. Therefore, Cell<&'a str> is invariant in 'a.
Exercise
Why can a shared reference usually shrink its lifetime, while &mut T cannot?
Show answer
Reading through &T cannot insert a shorter-lived value. Mutable access can write one, so invariance prevents a reference from being used with an unsafe lifetime.