Sub topic 4
Covariance: shrinking lifetimes through & and containers
This chapter assumes you know ownership, borrowing, basic lifetime annotations on functions and structs, and generics with trait bounds. Earlier chapters covered outlives bounds ('long: 'short) and lifetime subtyping. Here we apply that to the most common kind of variance.
What covariant means
A type constructor F<T> is covariant in T if F<Long> can be used wherever F<Short> is expected, whenever Long is a subtype of Short. For lifetimes, 'long: 'short means &'long T is a subtype of &'short T. A covariant type therefore lets the compiler shrink a lifetime inside it.
Shared references are covariant in both the lifetime and the referent:
&'a Tis covariant in'a.&'a Tis covariant inT.
Most owning containers are covariant in their element type too. That includes Box<T>, Vec<T>, Option<T>, [T; N] and tuples. So Vec<&'static str> can be used as Vec<&'a str>.
Worked example
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 function wants one 'a for both arguments. The borrow of outer lasts longer than the borrow of inner. Because &'a str is covariant, the compiler shrinks the borrow of outer to match the borrow of inner. A single 'a then covers both, and the result is valid only inside the inner block. No annotation is needed. The shrinking happens implicitly at the call.
Shrinking through containers
The same rule applies when the reference sits inside a container.
fn first_word<'a>(words: Vec<&'a str>) -> Option<&'a str> {
words.into_iter().next()
}
fn main() {
let literals: Vec<&'static str> = vec!["alpha", "beta"];
let local = String::from("gamma");
let mut mixed: Vec<&str> = literals;
mixed.push(&local);
println!("{:?}", first_word(mixed));
}literals has type Vec<&'static str>. Covariance lets it become Vec<&'x str>, where 'x is the shorter lifetime of local. Then push can add a shorter borrow. This is sound because the vector is owned and moved. Nobody keeps a handle that still expects 'static elements.
Why covariance is safe
Covariance is safe when a value is only read through the type. If you hold &'long T and treat it as &'short T, you can only get out things that are valid for at least 'short. Nothing can be written back that would break the original promise.
Once writing is possible through a shared handle, this argument fails. That is the subject of the next chapter, on &mut T and Cell<T>.
Quick reference
| Type | Covariant in `'a`? | Covariant in `T`? |
|---|---|---|
| `&'a T` | Yes | Yes |
| `Box<T>`, `Vec<T>`, `Option<T>` | Not applicable | Yes |
| `[T; N]`, `(T, U)` | Not applicable | Yes |
| `&'a mut T` | Yes | No (invariant) |
Exercise
Given let s: &'static str = "hi";, can you pass s to a function fn f<'a>(x: &'a str, y: &'a str) along with a borrow of a local String? Which property makes this work?
Show answer
Yes. &'static str is covariant in its lifetime, so the compiler shrinks it to the shorter lifetime of the local borrow. A single 'a then fits both arguments.