Sub topic 15
Subtyping and Variance of Lifetimes
This chapter assumes you can write lifetime annotations on functions, structs, and impl blocks. It also assumes you know &T versus &mut T, and that you have seen T: 'a bounds. Variance rarely appears in everyday code. It explains why some programs that look safe are rejected, and why a few compiler errors seem to blame the wrong line.
Lifetimes form a subtyping relation
Rust lifetimes have a subtyping relation. If 'long: 'short (read "'long outlives 'short"), then 'long is a subtype of 'short. A longer-lived region can stand in wherever a shorter one is expected. 'static is a subtype of every other lifetime.
This extends to types that contain lifetimes. &'long str is a subtype of &'short str, so the compiler may shrink the lifetime of a reference silently:
fn pick<'a>(x: &'a str, _y: &'a str) -> &'a str {
x
}
fn main() {
let outer = String::from("outer");
let r1: &str = &outer;
{
let inner = String::from("inner");
// 'a is chosen as the shorter region. r1 is shrunk to fit.
let result = pick(r1, &inner);
println!("{result}");
}
}This is why longest from earlier chapters accepts arguments with different real lifetimes. The compiler picks one 'a that both arguments can be shrunk to. You never write the coercion.
Variance: how subtyping carries through a type
Variance describes how the subtyping of a parameter affects the subtyping of the type built from it. Take a type F<T>, where T may be a lifetime or a type containing one:
- Covariant: if
Ais a subtype ofB, thenF<A>is a subtype ofF<B>. The relation goes the same way. - Contravariant:
F<B>is a subtype ofF<A>. The relation flips. - Invariant: no relation.
F<A>can only be used as exactlyF<A>.
| 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` |
Most types you meet are covariant, which is why lifetimes seem to "just shrink". The exceptions all involve some way to write through the reference.
Why `&mut T` is invariant in `T`
If &'a mut T were covariant in T, you could write a short-lived reference into a slot that promises to hold a long-lived one. The following function is legal on its own:
fn overwrite<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut long_lived: &'static str = "static";
{
let s = String::from("short");
// overwrite(&mut long_lived, &s);
// error[E0597]: `s` does not live long enough
}
println!("{long_lived}");
}Suppose the commented call compiled. long_lived would then hold a reference to s, which is dropped at the end of the inner block, and the println! would read freed memory. The compiler prevents this because &mut &'static str is invariant. It cannot be treated as &mut &'short str, so 'a is forced to be 'static, and &s cannot be 'static.
The shared-reference version is fine because nobody can write through &&'static str. Shrinking is safe when the data can only be read. The rule is: a position that is only read can be covariant, a position that is only written can be contravariant, and a position that is both must be invariant.
Cell<T> and RefCell<T> are invariant for the same reason. They allow writes through a shared reference.
Contravariance in function arguments
A function that accepts any &str can stand in for a function that only needs to accept &'static str. A function that insists on &'static str cannot stand in for one that must handle local references. That reversal is contravariance:
fn takes_static(s: &'static str) {
println!("static: {s}");
}
fn takes_any(s: &str) {
println!("any: {s}");
}
fn call_with_local(f: fn(&str), s: &str) {
f(s);
}
fn main() {
let owned = String::from("local");
call_with_local(takes_any, &owned);
// call_with_local(takes_static, &owned); // error[E0308]: mismatched types
takes_static("literal");
}Contravariance over lifetimes is rare in practice. Because fn(&str) is already higher-ranked (it means for<'a> fn(&'a str)), you mostly see it as the error above.
How variance is computed for your own types
You do not declare variance. The compiler infers it from the fields of a struct. If a lifetime appears only in covariant positions, the struct is covariant in it. One invariant use makes the whole struct invariant in that parameter.
#![allow(dead_code)]
use std::cell::Cell;
use std::marker::PhantomData;
struct Covariant<'a> {
r: &'a str,
}
struct Invariant<'a> {
c: Cell<&'a str>,
}
struct CovariantMarker<'a> {
_p: PhantomData<&'a ()>,
}
struct InvariantMarker<'a> {
_p: PhantomData<Cell<&'a ()>>,
}
fn shrink<'long: 'short, 'short>(c: Covariant<'long>) -> Covariant<'short> {
c
}
// fn shrink_inv<'long: 'short, 'short>(c: Invariant<'long>) -> Invariant<'short> {
// c // error: lifetime may not live long enough
// }
fn main() {
let c = Covariant { r: "hi" };
println!("{}", shrink(c).r);
}PhantomData<T> is how you tell the compiler about a lifetime or type that the struct logically uses but does not store. It behaves as if the struct held a T, so the variance of the PhantomData argument becomes the variance of your parameter. Use PhantomData<Cell<&'a ()>> or PhantomData<fn(&'a ()) -> &'a ()> when you need invariance, for example in an unsafe API that hands out branded lifetimes.
The same inference applies to trait objects. Box<dyn Trait + 'a> is covariant in 'a, so a boxed closure that borrows a long-lived value can be used where a shorter bound is required.
The `&'a mut self` trap
Invariance is the reason one lifetime mistake is so punishing. When a method takes &'a mut self and Self is Counter<'a>, the borrow of self must last as long as 'a. Because &mut Counter<'a> is invariant in 'a, the compiler cannot shorten either lifetime to make the borrow end sooner.
struct Counter<'a> {
text: &'a str,
pos: usize,
}
impl<'a> Counter<'a> {
// Wrong: ties the borrow of self to the struct's own lifetime parameter.
// fn bump(&'a mut self) { self.pos += 1; }
// Right: the borrow of self is an independent, short lifetime.
fn bump(&mut self) {
self.pos += 1;
}
fn rest(&self) -> &'a str {
&self.text[self.pos..]
}
}
fn main() {
let mut c = Counter { text: "abc", pos: 0 };
c.bump();
c.bump();
println!("{}", c.rest());
}With the commented version, the second c.bump() fails with E0499: cannot borrow c as mutable more than once at a time. The first call borrows c for as long as 'a, which is as long as c is used. The error points at the call site, but the cause is the signature.
Practical guidance
- Treat variance as a diagnostic tool. When the compiler refuses to shrink a lifetime, check for
&mut,Cell,RefCell, or raw*mutalong the path. - Avoid
&'a mut T<'a>unless you are deliberately making a borrow last as long as the value. - Prefer separate lifetime parameters when one value is written through and another is only read.
- You cannot override inferred variance on safe types. Control it by choosing field types and
PhantomData. - Variance matters most to library authors writing
unsafecode, such as custom collections and arenas. A wrong marker can make a type covariant when it must be invariant, which is unsound.
Exercise
A struct has the field slot: &'a mut Vec<&'a str>. Is the struct covariant in 'a? Explain which part decides the answer.
Show answer
No. &'a mut T is invariant in T, and here T is Vec<&'a str>, which contains 'a. So 'a appears in an invariant position and the struct is invariant in 'a. The outer &'a mut being covariant in its own lifetime does not help, because one invariant use is enough.
Exercise
Why does the compiler accept let r: &'short str = long_ref; where long_ref: &'long str, but reject passing &mut long_ref where a &mut &'short str is expected?
Show answer
&'long str is a subtype of &'short str, because shared references are covariant and can only be read. &mut &'long str is not a subtype of &mut &'short str, because &mut is invariant in its target type. If it were allowed, the callee could write a short-lived reference into long_ref, leaving a dangling reference once the short-lived data is dropped.