Level 4 · Expert· Lesson 2 of 9 · 30 min
Subtyping and variance
Lifetimes as a subtype relation, covariance, contravariance and invariance, and why &mut T must be invariant.
Variance is the part of the type system that decides when one generic type may be used in place of another. You have relied on it in every program that passes a &'static str where a &'a str is expected. When you write unsafe code with raw pointers, you become responsible for choosing it.
Lifetime subtyping
Rust has no inheritance, but it does have subtyping — on lifetimes. 'long: 'short reads “'long outlives 'short”, and it makes 'long a subtype of 'short: anything valid for the longer region is certainly valid for the shorter one.
fn shorter<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() <= b.len() { a } else { b }
}
fn main() {
let forever: &'static str = "static text";
let local = String::from("local");
// `forever` is &'static str but is accepted as &'a str for the shorter 'a of `local`.
println!("{}", shorter(forever, &local));
}
'static outlives everything, so it is a subtype of every lifetime.
Variance
Given a type constructor F<T> and Sub a subtype of Super:
Fis covariant ifF<Sub>is a subtype ofF<Super>— the relation passes through.Fis contravariant ifF<Super>is a subtype ofF<Sub>— the relation flips.Fis invariant if neither holds — the types must match exactly.
| Type | in 'a |
in T |
|---|---|---|
&'a T |
covariant | covariant |
&'a mut T |
covariant | invariant |
Box<T>, Vec<T>, Option<T> |
covariant | |
*const T, NonNull<T> |
covariant | |
*mut T |
invariant | |
Cell<T>, RefCell<T>, UnsafeCell<T>, Mutex<T> |
invariant | |
fn(T) -> U |
contravariant in T, covariant in U |
|
PhantomData<T> |
covariant | |
dyn Trait<T> + 'a |
covariant | invariant |
The pattern: read-only access is covariant; anything that lets you write is invariant; consuming positions are contravariant.
Why &mut T is invariant in T
Suppose it were covariant. Then &mut &'static str could be passed where &mut &'a str is expected:
fn overwrite<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut forever: &'static str = "static";
{
let short = String::from("short-lived");
overwrite(&mut forever, &short); // ❌ error[E0597]: `short` does not live long enough
}
println!("{forever}"); // would read freed memory
}
With covariance the compiler would shrink &mut &'static str to &mut &'a str, the function would store a short-lived reference in forever, and the last line would be a use-after-free. Invariance forces 'a to be exactly 'static, which short cannot satisfy. The error message is variance at work.
The same reasoning explains Cell<T> and every other interior-mutability type: a shared &Cell<T> permits writing, so it must not be covariant.
Note that &'a mut T remains covariant in 'a: shortening how long you hold an exclusive borrow is always safe.
Contravariance
Function arguments are the only source of contravariance. A function that can handle any lifetime can be used where a function handling only 'static is required:
fn print_any<'a>(s: &'a str) {
println!("{s}");
}
fn main() {
// A fn(&'a str) for all 'a is usable as a fn(&'static str):
let f: fn(&'static str) = print_any;
f("hello");
}
Going the other way — using a function that requires 'static input where arbitrary input may arrive — would be unsound, and is rejected.
Variance of your own types
Variance is inferred from fields. A struct is covariant in a parameter only if every use of that parameter is covariant; one invariant use makes the whole struct invariant.
use std::cell::Cell;
struct Reader<'a> { data: &'a str } // covariant in 'a
struct Slot<'a> { data: Cell<&'a str> } // invariant in 'a
fn shrink_reader<'short>(r: Reader<'static>) -> Reader<'short> {
r // OK: covariance lets Reader<'static> become Reader<'short>
}
// fn shrink_slot<'short>(s: Slot<'static>) -> Slot<'short> { s }
// ❌ would not compile: Slot is invariant, so the lifetimes must match exactly.
fn main() {
let r = shrink_reader(Reader { data: "x" });
let s = Slot { data: Cell::new("y") };
println!("{} {}", r.data, s.data.get());
}
When a struct holds only raw pointers, the compiler has no field to infer from — a parameter that appears nowhere is an error (E0392). You state the intended relationship with PhantomData:
| You want | Write |
|---|---|
Covariant, owns a T (affects drop check) |
PhantomData<T> |
| Covariant, does not own | PhantomData<fn() -> T> or PhantomData<*const T> |
| Contravariant | PhantomData<fn(T)> |
| Invariant | PhantomData<fn(T) -> T> or PhantomData<*mut T> |
| Tie to a lifetime, covariant | PhantomData<&'a T> |
| Tie to a lifetime, invariant | PhantomData<&'a mut T> or PhantomData<Cell<&'a ()>> |
The pointer forms also remove Send and Sync; the fn forms do not. Choose with both effects in mind.
A real soundness consequence
If you implement a collection with *mut T, it is invariant by default — safe but unnecessarily strict: users cannot pass a MyVec<&'static str> where a MyVec<&'a str> is expected. The standard library uses NonNull<T>, which is covariant, plus PhantomData<T> to express ownership.
The opposite mistake is the dangerous one. A cell-like type that hands out write access through &self but is declared covariant lets safe code reproduce the overwrite exploit above. When in doubt, be invariant.
Invariant lifetimes are also a tool: because an invariant lifetime cannot be unified with any other, it can serve as a unique compile-time brand. The GhostCell design (Yanovski et al., ICFP 2021) uses a branded lifetime to separate permission from data, giving safe, zero-cost shared mutation.
Exercises
- For each type state the variance in each parameter, then confirm by writing a coercion function that compiles or fails:
struct A<'a, T>(&'a T),struct B<'a, T>(&'a mut T),struct C<T>(fn(T)),struct D<T>(fn() -> T),struct E<T>(fn(T) -> T). - Explain why
Vec<&'static str>can be passed tofn f<'a>(v: Vec<&'a str>)but&mut Vec<&'static str>cannot be passed tofn g<'a>(v: &mut Vec<&'a str>, s: &'a str)together with a local string. - Define
struct MyBox<T> { ptr: *mut T }. Show a use that fails due to invariance; fix it withNonNull<T>. - Read the “Subtyping and Variance” chapter of the Rustonomicon and reproduce its
assignexample.
Answers to 1
A: covariant in 'a and T. B: covariant in 'a, invariant in T. C: contravariant in T. D: covariant in T. E: invariant in T (it appears in both a contravariant and a covariant position).
Check your understanding
Pick an answer to see the explanation.
1.Which statement about lifetime subtyping is correct?
2.What is the variance of
&'a mut TinT?3.What is the variance of
fn(T) -> U?