Sub topic 4
Covariance: shrinking lifetimes through & and containers
This chapter assumes you can read lifetime annotations on functions and structs. It also assumes you know what 'long: 'short ("'long outlives 'short") means. It builds on the previous chapters on outlives bounds and lifetime subtyping. Here you will see the most common form of variance, covariance, and learn to predict where the compiler will shrink a lifetime for you.
The idea in one sentence
A type constructor F<'a> is covariant in 'a if 'long: 'short implies that F<'long> is a subtype of F<'short>. Anywhere the compiler needs an F<'short>, it accepts an F<'long>.
The direction matters. A longer-lived value can stand in for a shorter-lived one. The reverse is never allowed, because a value that only lives briefly cannot promise to live longer.
A first example: two borrows, one lifetime
longest takes two references and returns one of them. Both parameters share the single lifetime 'a.
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 r = longest(&outer, &inner);
println!("{r}");
}
}The borrow &outer is valid for a long stretch of main. The borrow &inner is valid only inside the inner block. A single 'a cannot be both. The compiler solves this by shrinking: &'long String is a subtype of &'short String, so the outer borrow is treated as if it had the shorter lifetime. Then 'a is the inner block, and both arguments fit.
Nothing in the source code asks for this. The shrinking happens during type checking, at the function call. It does not change the value or copy anything. Only the lifetime in the type is narrowed.
The same call also shows the cost of shrinking. The result r has the shorter lifetime, so it cannot escape the inner block:
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 r;
{
let inner = String::from("short");
r = longest(&outer, &inner);
} // error: `inner` does not live long enough
println!("{r}");
}This version does not compile. The compiler cannot know which argument longest returns, so r must be valid wherever either argument would be valid. That is the shorter one.
Why shrinking a shared reference is safe
A shared reference &'a T only lets you read. If you hold a reference that is valid for a long time, you can treat it as valid for a shorter time and nothing breaks. Every read through the reference happens inside the shorter window anyway.
This reasoning also covers the T inside the reference. &'a T is covariant in 'a and in T. So &'a &'static str can be used as &'a &'b str when 'static: 'b. The inner reference is also read-only through the outer one, so shrinking it is safe too.
Containers that own their contents
Covariance carries through types that own or hold values of T. If T can shrink, so can the container.
fn main() {
let words: Vec<&'static str> = vec!["alpha", "beta"];
let local = String::from("gamma");
// The type annotation lets the compiler pick a shorter lifetime.
let mut mixed: Vec<&str> = words;
mixed.push(&local);
println!("{mixed:?}");
}words has type Vec<&'static str>. Because Vec<T> is covariant in T, it is a subtype of Vec<&'x str>, where 'x is the region in which local is borrowed. The move into mixed therefore type-checks, and the compiler can then push a borrow of a local String into the vector. This works only because words was moved. The original Vec<&'static str> is gone, so nobody can still expect every element to be 'static.
Which types are covariant
| Type | Variance in `'a` | Variance in `T` |
|---|---|---|
| `&'a T` | covariant | covariant |
| `Box<T>`, `Vec<T>`, `Option<T>` | n/a | covariant |
| `Rc<T>`, `Arc<T>` | n/a | covariant |
| `[T; N]`, `(T, U)` | n/a | covariant |
| `*const T` | n/a | covariant |
| `fn() -> T` | n/a | covariant |
| `&'a mut T` | covariant | invariant |
| `Cell<T>`, `RefCell<T>` | n/a | invariant |
The last two rows are previews. Mutable references are covariant in their own lifetime 'a but invariant in the type they point to. Interior mutability makes Cell<T> invariant in T. The next chapter explains why. Contravariant positions, such as function arguments, come after that.
Shrinking happens at use sites
Covariance does not change a variable's declared type. It lets the compiler accept a value where a type with a shorter lifetime is expected. In practice you meet it in three places:
- Function arguments, as in
longest. - Assignments and
letbindings with a type annotation, as inmixedabove. - Returns, where a longer-lived reference is returned from a function whose signature promises a shorter one.
Often you will not notice any of this. You notice it only when the compiler picks a shorter lifetime than you wanted. A longer lifetime on an argument never causes an error. A shorter lifetime in the result is what restricts how long the result can be used.
Common mistakes
- Expecting a lifetime to grow.
&'short stris never accepted where&'static stris required. If a function demands'static, a borrow of a local will fail, however the code is arranged. - Blaming the callee for a short result. When
longestreturns something that "does not live long enough", the cause is usually the shorter of the two arguments. Check which argument has the shorter borrow. - Assuming containers always shrink.
Vec<&'static str>shrinks becauseVec<T>is covariant inT. A container that exposes mutation through its type parameter, such asCell<&'static str>, does not. See the next chapter. - Reading
'long: 'shortbackwards. The lifetime on the left lasts at least as long as the one on the right. The type with the longer lifetime is the subtype.
Exercises
Exercise
Given fn show<'a>(items: Vec<&'a str>) and a variable v: Vec<&'static str>, does show(v) compile? Why?
Show answer
Yes. Vec<T> is covariant in T, and &'a str is covariant in 'a. So Vec<&'static str> is a subtype of Vec<&'a str> for any 'a, and the compiler shrinks 'static to 'a at the call.
Exercise
In let r = longest(&outer, &inner);, outer lives for all of main and inner lives only in an inner block. Why can r not be used after that block, even if outer happens to be the longer string?
Show answer
Both arguments share one lifetime 'a, and the compiler must pick a region valid for both borrows. That region is the shorter one, the inner block. The result is typed &'a str with that 'a, so using it after the block is an error. The compiler does not track which argument is actually returned at runtime.