Sub topic 7
How the compiler computes variance for your types
Earlier chapters showed that &'a T is covariant, &mut T is invariant in T, and function arguments run the other way. This chapter covers how the compiler works out the variance of types you define yourself. It assumes you know generics, basic lifetime annotations on structs, and the covariant, contravariant and invariant vocabulary from the previous chapters.
Variance is computed, not declared
Rust has no syntax for writing "this struct is covariant in 'a". The compiler infers variance from the struct or enum definition. It looks at every field and every place a lifetime or type parameter appears, and derives one result per parameter.
Two consequences follow:
- Variance is per parameter.
struct Pair<'a, T>can be covariant in'aand invariant inT. - Variance comes from the fields, not from trait bounds. A
where T: Cloneclause does not change it.
The algorithm in three steps
- For each field, find every occurrence of the parameter.
- Work out the variance of each occurrence by composing the variances of the type constructors wrapped around it.
- Combine the results from all occurrences into one variance for the parameter.
Step 2: composing through wrappers
Each type constructor has a variance in each of its parameters. When a parameter sits inside several constructors, the variances compose like signs in multiplication.
| Wrapper's variance | Inner occurrence is covariant | Inner occurrence is contravariant | Inner occurrence is invariant |
|---|---|---|---|
| Covariant wrapper | covariant | contravariant | invariant |
| Contravariant wrapper | contravariant | covariant | invariant |
| Invariant wrapper | invariant | invariant | invariant |
For example, fn(&'a str) is contravariant in 'a. Put that inside another fn(...) argument, giving fn(fn(&'a str)). The contravariant wrapper flips it, so the result is covariant in 'a.
Step 3: combining occurrences
If every occurrence has the same variance, the parameter gets that variance. If occurrences disagree, for example one covariant and one contravariant, the result is invariant. Any invariant occurrence makes the whole parameter invariant.
Invariance is the safe fallback. A type that is invariant accepts no substitution, so it cannot be misused.
Variance of common building blocks
You rarely need to derive these by hand, because the standard library types follow a small set of patterns.
| Type | Variance in `'a` | Variance in `T` |
|---|---|---|
| `&'a T` | covariant | covariant |
| `&'a mut T` | covariant | invariant |
| `Box<T>`, `Vec<T>`, `Option<T>` | none | covariant |
| `Cell<T>`, `RefCell<T>`, `UnsafeCell<T>` | none | invariant |
| `*const T` | none | covariant |
| `*mut T` | none | invariant |
| `fn(T) -> U` | none | contravariant in `T`, covariant in `U` |
| `PhantomData<T>` | none | covariant |
Containers that own their contents are covariant. Anything that allows writing through a shared path, such as &mut, Cell or *mut, is invariant.
Worked examples
A covariant struct
A struct that only holds a shared reference is covariant in its lifetime. The compiler accepts the shrinking conversion in shrink.
struct Holder<'a> {
text: &'a str,
}
fn shrink<'long: 'short, 'short>(h: Holder<'long>) -> Holder<'short> {
h
}
fn main() {
let h = Holder { text: "hello" };
let s = shrink(h);
println!("{}", s.text);
}A contravariant struct
A struct that only stores a function pointer taking &'a str is contravariant in 'a. A function that can handle short-lived strings can also handle long-lived ones, so the conversion goes from a shorter lifetime to a longer one.
struct Callback<'a> {
f: fn(&'a str),
}
fn lengthen<'long: 'short, 'short>(c: Callback<'short>) -> Callback<'long> {
c
}
fn print_it(s: &str) {
println!("{s}");
}
fn main() {
let cb = Callback { f: print_it };
let cb: Callback<'static> = lengthen(cb);
(cb.f)("static text");
}One invariant field spoils the struct
Adding a Cell<&'a str> field makes Mixed invariant in 'a, even though the first field alone would be covariant.
use std::cell::Cell;
struct Mixed<'a> {
shared: &'a str,
slot: Cell<&'a str>,
}
// Does not compile: Mixed<'a> is invariant in 'a because of `slot`.
// fn shrink<'long: 'short, 'short>(m: Mixed<'long>) -> Mixed<'short> {
// m
// }
fn main() {
let m = Mixed { shared: "a", slot: Cell::new("b") };
m.slot.set("c");
println!("{} {}", m.shared, m.slot.get());
}Uncomment shrink and the compiler reports lifetime may not live long enough. This is the same invariance error you saw with &mut &'a str, now caused by a field in your own type.
Mixed co- and contravariance
Storing &'a str and fn(&'a str) in the same struct puts the parameter in a covariant place and a contravariant place. The occurrences disagree, so the struct is invariant in 'a. A callback paired with the data it consumes cannot change its lifetime in either direction.
Rules for enums, recursion and unused parameters
- An enum is analyzed over the fields of all its variants together. One invariant field in any variant makes the parameter invariant for the whole enum.
- A struct built from other generic types inherits their variance.
struct Wrapper<T> { items: Vec<T> }is covariant inTbecauseVec<T>is. - Recursive types are solved as a fixed point. The compiler starts by assuming every parameter is unconstrained, then tightens the result until it stops changing.
- Every parameter must be used. A parameter that appears in no field is an error (
E0392), because the compiler would have nothing to infer its variance from.PhantomDatais the usual fix, covered in the next chapter. - A projection such as
<T as Iterator>::Itemin a field makesTinvariant, because the compiler cannot reason about how the associated type depends onT.
Checking the result
You can test the variance the compiler inferred by writing a small conversion function like shrink above and seeing whether it compiles. This is a useful habit when you suspect a struct is invariant. Keep such functions in a test module so a refactor that changes variance is caught.
If a lifetime error mentions that a lifetime "must outlive 'static" or "may not live long enough" for a type of your own, check its fields for &mut, Cell, RefCell, *mut or a function pointer that takes the lifetime as an argument.
Exercise
What variance does struct Visitor<'a, T> { cb: fn(T), r: &'a T } have in 'a and in T?
Show answer
It is covariant in 'a, because 'a appears only in &'a T, a covariant position. It is invariant in T. T appears covariantly in &'a T and contravariantly as the argument of fn(T). Mixed occurrences combine to invariant.
Exercise
Why does struct Slot<'a> { p: *mut &'a str } not shrink its lifetime, even though &'a str alone is covariant?
Show answer
The lifetime sits inside *mut T, which is invariant in T. Composing any variance with an invariant wrapper gives invariant, so Slot<'a> is invariant in 'a.