Sub topic 3
What variance means
This chapter assumes you know ownership and borrowing, basic lifetime annotations on functions and structs, and generics with trait bounds. It also assumes you have seen 'long: 'short written as an outlives bound. Here we define variance and set up the vocabulary. The next chapters take covariance, invariance and contravariance one at a time.
The question variance answers
Lifetime subtyping tells you that a reference valid for a long time can be used where a shorter-lived reference is expected. Variance extends that to types built from references. Suppose 'long outlives 'short. Is a Vec<&'long str> usable where a Vec<&'short str> is expected? What about a Cell<&'long str>, an &mut &'long str, or a function that takes &'long str?
The answer is not the same for all of these, and it can't be. Variance is the rule that says, for each type constructor and each parameter, how the subtyping relationship of the argument carries over to the whole type.
Subtyping as substitution
Write S <: T for "S is a subtype of T", meaning a value of type S can be used wherever a T is required. In Rust the subtyping that matters in daily code comes from lifetimes. If 'long: 'short, then:
&'long str <: &'short str
The longer lifetime gives the subtype. A longer-lived reference promises more, so it can stand in for one that promises less.
fn shorten<'long: 'short, 'short>(x: &'long str) -> &'short str {
x
}
fn main() {
let owned = String::from("hello");
let r: &str = shorten(&owned);
println!("{r}");
}The body is just x. The compiler accepts it because &'long str is a subtype of &'short str, so it inserts the coercion for you.
The three kinds of variance
Take a type constructor F<T>, such as Vec<T> or fn(T). Suppose Sub <: Super. Variance describes how F<Sub> and F<Super> relate.
| Variance | Relationship | Meaning |
|---|---|---|
| Covariant | `F<Sub> <: F<Super>` | The subtyping direction is preserved. |
| Contravariant | `F<Super> <: F<Sub>` | The subtyping direction is reversed. |
| Invariant | No relationship | The argument must match exactly. |
Variance is a property of a type constructor with respect to one specific parameter. A type with several parameters can have a different variance in each. For example, &'a mut T is covariant in 'a and invariant in T.
The block above is only a placeholder to keep the chapter's constructs in order. The real diagram follows.
Why Rust needs all three
It would be simpler if every type were covariant. That is unsound, because some types let you write through the reference. The borrow checker's guarantees depend on the type system never letting a short-lived value be stored where a long-lived one is expected.
Think of what each type allows you to do with its parameter:
- A type that only produces values of
Tis safe to treat covariantly. If you can only read a&'long str, then handing out a&'short strview loses nothing. - A type that only consumes values of
Tis contravariant. A function that accepts any&'short stris also happy to accept a&'long str, so it can be used where a function over&'long stris expected. - A type that both reads and writes
Tmust be invariant. If it could shrink, someone could write a short-lived value into a slot that other code believes holds a long-lived one. If it could grow, someone could read a value that no longer satisfies the promise made to the reader.
This is why &T is covariant in T, fn(T) is contravariant in T, and &mut T is invariant in T.
A common reference table
| Type | Variance in `'a` | Variance in `T` |
|---|---|---|
| `&'a T` | covariant | covariant |
| `&'a mut T` | covariant | invariant |
| `Box<T>`, `Vec<T>`, `Option<T>` | not applicable | covariant |
| `*const T` | not applicable | covariant |
| `*mut T` | not applicable | invariant |
| `Cell<T>`, `RefCell<T>`, `UnsafeCell<T>` | not applicable | invariant |
| `fn(T) -> U` | not applicable | contravariant in `T`, covariant in `U` |
Each row gets its own treatment in later chapters. For now, notice the pattern: containers that own or share data without allowing mutation through a shared handle are covariant, and anything that permits writing through a reference is invariant.
Seeing the three behaviors
Covariance is what shorten showed above. Contravariance works on function pointers. A function that accepts any short-lived string can be used where one that accepts a long-lived string is expected.
fn widen<'long: 'short, 'short>(f: fn(&'short str)) -> fn(&'long str) {
f
}
fn print_it(s: &str) {
println!("{s}");
}
fn main() {
let g: fn(&'static str) = widen(print_it);
g("static text");
}The direction reversed. &'long str <: &'short str, but fn(&'short str) <: fn(&'long str).
Invariance is the case where the compiler refuses. The function below is shown commented out because it does not compile.
// Does not compile: &mut T is invariant in T.
// fn shrink_mut<'long: 'short, 'short, 'r>(
// x: &'r mut &'long str,
// ) -> &'r mut &'short str {
// x
// }
fn main() {
let mut s: &str = "hello";
let r: &mut &str = &mut s;
*r = "world";
println!("{s}");
}If shrink_mut were allowed, a caller could write a short-lived &'short str through the returned reference. After the call, the original &'long str variable would hold a dangling pointer.
Where you notice variance
Most of the time variance works silently. You notice it in three situations:
- A reference shrinks without a visible cast. Passing
&outerand&innertolongestcompiles because covariance shrinks the longer borrow. - A
&mutrefuses to shrink. The error often reads "does not live long enough" or "lifetime may not live long enough", and the cause is thatTin&mut Tis invariant, so the lifetime inside it must match exactly. - You define your own generic type. The compiler computes the variance of your struct from its fields, and you may need
PhantomDatato choose a different one. Both topics have their own chapters.
Summary of the vocabulary
'long: 'shortmeans'longoutlives'short, and&'long T <: &'short T.- Covariant keeps the subtyping direction, contravariant reverses it, and invariant allows no substitution at all.
- Variance is a per-parameter property of a type constructor.
- Producing values suggests covariance, consuming values suggests contravariance, and doing both forces invariance.
Exercise
Suppose 'long: 'short. For each type, say whether the first can be used where the second is expected: (a) Vec<&'long str> for Vec<&'short str>, (b) fn(&'long str) for fn(&'short str), (c) Cell<&'long str> for Cell<&'short str>.
Show answer
(a) Yes. Vec<T> is covariant in T, and &'long str <: &'short str. (b) No. fn(T) is contravariant in T, so the usable direction is the other one: fn(&'short str) can be used where fn(&'long str) is expected. (c) No. Cell<T> is invariant in T because it allows writing through a shared reference, so the argument must match exactly.
Exercise
Why can &mut &'long str not be shrunk to &mut &'short str, even though &'long str can be shrunk to &'short str?
Show answer
A &mut reference lets the holder write a new value into the slot. If the slot's type were viewed as &'short str, a caller could store a short-lived reference in it. The original owner still believes the slot holds a &'long str, so that reference would dangle once 'short ends. Making &mut T invariant in T prevents this.