Sub topic 15
Subtyping and variance (advanced)
This chapter assumes you can write function signatures with explicit lifetimes, you know the difference between &T and &mut T, and you have seen compiler errors such as E0597. Variance explains a few cases where the compiler accepts or rejects lifetime code that otherwise looks surprising.
Lifetimes as subtypes
Lifetimes form a subtype relationship. If 'long: 'short (read "'long outlives 'short"), then a reference valid for 'long can be used wherever a reference valid for 'short is expected. The compiler shortens a lifetime silently when it needs to.
You rely on this whenever a call mixes references of different ages:
fn pick_first<'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");
let result = pick_first(r1, &inner);
println!("{result}");
}
}r1 lives longer than inner. The compiler picks 'a as the inner scope and treats r1 as a reference with that shorter lifetime.
What variance means
Variance describes how a type constructor treats this relationship. For a type F<T>:
- Covariant: if
Ais a subtype ofB, thenF<A>is a subtype ofF<B>. The direction is preserved. - Contravariant: the direction is reversed.
- Invariant: no substitution is allowed. The types must match exactly.
| Type | Variance in `'a` | Variance in `T` |
|---|---|---|
| `&'a T` | covariant | covariant |
| `&'a mut T` | covariant | invariant |
| `Box<T>`, `Vec<T>` | not applicable | covariant |
| `Cell<T>`, `RefCell<T>` | not applicable | invariant |
| `fn(T) -> U` | not applicable | contravariant in `T`, covariant in `U` |
Why `&mut T` is invariant in `T`
Shared references only let you read, so shortening what they point to is harmless. A mutable reference lets you write. If &mut &'static str could shrink to &mut &'short str, you could store a short-lived reference into a slot that the rest of the program believes holds a 'static one.
fn overwrite<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut s: &'static str = "static";
let local = String::from("local");
overwrite(&mut s, &local);
println!("{s}");
}
// error[E0597]: `local` does not live long enoughBecause T = &'static str cannot change behind &mut, 'a is forced to be 'static, and local is not. Remove the 'static annotation and the program compiles. The compiler can then infer a shorter lifetime for s itself:
fn overwrite<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let local = String::from("local");
let mut s: &str = "static";
overwrite(&mut s, &local);
println!("{s}");
}Practical consequences
- An error that says a lifetime "must outlive
'static" or "is invariant" usually points at a&mutor interior mutability (Cell,RefCell,Mutex) wrapped around a reference. - Prefer
&'a mut Vec<&'b str>with separate lifetimes over reusing one'afor both. This is the multiple-lifetimes technique from earlier chapters, and invariance is the reason it matters. - Mutable data structures that hold references are more rigid than their shared counterparts. Expect to be more explicit with lifetimes there.
Exercise
The type &'a mut Vec<&'static str> is passed to a function that expects &'a mut Vec<&'short str>. Does it compile, and why?
Show answer
No. &mut T is invariant in T, so Vec<&'static str> cannot be treated as Vec<&'short str>. If it could, the function could push a short-lived reference into a vector the caller believes holds only 'static strings. The outer 'a is covariant and may shrink, but the inner T must match exactly.