Sub topic 7
How the compiler computes variance for your types
This chapter assumes you know the three kinds of variance (covariant, contravariant, invariant) and why &mut T and Cell<T> are invariant. Here you will see how the compiler works out the variance of your own structs and enums.
You do not declare variance
Rust has no syntax for writing variance on a type. The compiler infers it from the fields. For each lifetime or type parameter, it looks at every place the parameter appears and combines the results.
The rules
Each field gives its parameter a variance based on the field's type. The compiler then merges the results:
- If every use is covariant, the struct is covariant in that parameter.
- If every use is contravariant, the struct is contravariant.
- If the uses disagree, or any use is invariant, the struct is invariant.
The position of a parameter also matters. Nesting a type inside a contravariant position flips its variance, and nesting inside an invariant position makes it invariant.
| Field type | Variance in `'a` or `T` |
|---|---|
| `&'a T` | covariant in `'a` and `T` |
| `&'a mut T` | covariant in `'a`, invariant in `T` |
| `Box<T>`, `Vec<T>`, `Option<T>` | covariant in `T` |
| `Cell<T>`, `RefCell<T>`, `UnsafeCell<T>` | invariant in `T` |
| `fn(T) -> U` | contravariant in `T`, covariant in `U` |
| `*const T` | covariant in `T` |
| `*mut T` | invariant in `T` |
Worked example
use std::cell::Cell;
struct Shared<'a> {
text: &'a str,
}
struct Callback<'a> {
f: fn(&'a str) -> usize,
}
struct Mixed<'a> {
text: &'a str,
cell: Cell<&'a str>,
}
fn shrink<'long: 'short, 'short>(x: Shared<'long>) -> Shared<'short> {
x
}
fn lengthen<'long: 'short, 'short>(x: Callback<'short>) -> Callback<'long> {
x
}
// Does not compile: Mixed is invariant in 'a.
// fn shrink_mixed<'long: 'short, 'short>(x: Mixed<'long>) -> Mixed<'short> {
// x
// }
fn main() {
let s = Shared { text: "hi" };
println!("{}", shrink(s).text);
let c = Callback { f: str::len };
println!("{}", (lengthen(c).f)("four"));
}Shared is covariant because &'a str is. Callback is contravariant because 'a sits in a function argument. That is why lengthen goes from 'short to 'long, the opposite direction of shrink. Mixed uses 'a covariantly in text and invariantly in cell. The merge rule makes the whole struct invariant.
Unused parameters are an error
If a parameter appears in no field, the compiler has nothing to infer from. It rejects the type with error E0392, "parameter is never used". That includes lifetimes. The next chapter shows how PhantomData fixes this and lets you choose the variance.
Inference through other types
Variance also flows through generic types you use as fields. Vec<&'a str> is covariant in 'a because Vec<T> is covariant in T. Cell<Vec<&'a str>> is invariant in 'a because Cell<T> is invariant in T.
Exercise
A struct has two fields: a: &'a str and b: fn(&'a str). What is its variance in 'a, and why?
Show answer
Invariant. The first field is covariant in 'a and the second is contravariant. When the uses disagree, the compiler merges them into invariance.