Sub topic 3
What variance means
This chapter assumes you know ownership and borrowing, basic lifetime annotations, and generics with trait bounds. It also assumes you have seen that 'long: 'short means "'long outlives 'short". The previous chapter showed that a longer lifetime can stand in for a shorter one. This chapter asks how that substitution carries over to types built from lifetimes.
The question variance answers
Write A <: B to mean "A is a subtype of B", so a value of type A can be used where a B is expected. In Rust, subtyping is mostly about lifetimes. If 'long: 'short, then 'long <: 'short. The longer lifetime is the subtype, because a reference valid for longer is safe wherever a shorter one is needed.
Now take a type constructor F<T>, such as Vec<T> or &'a T. Suppose you know Long <: Short. Variance tells you whether F<Long> and F<Short> are related, and in which direction.
The three kinds
| Kind | Rule | Examples |
|---|---|---|
| Covariant | `Long <: Short` gives `F<Long> <: F<Short>` | `&'a T`, `Vec<T>`, `Box<T>` |
| Contravariant | `Long <: Short` gives `F<Short> <: F<Long>` | `T` in `fn(T)` |
| Invariant | No relation between `F<Long>` and `F<Short>` | `T` in `&mut T`, `Cell<T>` |
Variance belongs to a type constructor and to one specific parameter. For example, &'a mut T is covariant in 'a but invariant in T.
Covariance in practice
Covariance is the case you use without noticing. This function compiles because &'long str is covariant in its lifetime, so the compiler shrinks it:
fn shrink<'long: 'short, 'short>(s: &'long str) -> &'short str {
s
}
fn main() {
let text = String::from("hello");
let r: &str = shrink(&text);
println!("{r}");
}The same shrinking works through owning containers. A Vec<&'long str> can be used as a Vec<&'short str> when you only read from it.
Why the rules exist
Variance is a safety rule, not a convenience. A type may only be shrunk or widened in a direction that cannot be used to smuggle in a dangling reference. Read-only positions are safe to shrink, so they are covariant. Positions that both read and write are unsafe to change in either direction, so they are invariant. Function arguments are written to by the caller, which is why they run the other way.
The later chapters on invariance and contravariance explain each case in detail. For now, remember one question to ask of any type: in this parameter, does the type only produce values, only consume them, or both?
- Produces only: covariant.
- Consumes only: contravariant.
- Both: invariant.
Exercise
A function takes x: Vec<&'static str> and returns Vec<&'a str> for some shorter 'a, with the body just x. Does this compile? Name the variance involved.
Show answer
Yes. Vec<T> is covariant in T, and &'static str <: &'a str because 'static outlives every 'a. So Vec<&'static str> can be used as Vec<&'a str>.