Sub topic 5
Invariance: why &mut T and Cell<T> cannot shrink
This chapter assumes you know references, lifetime annotations, and the covariance rule from the previous chapter. There, &'long T could be used where &'short T was expected. Invariance is the case where that substitution is forbidden.
What invariant means
A type is invariant in a parameter when the compiler accepts only that exact parameter. A longer lifetime cannot stand in for a shorter one, and a shorter one cannot stand in for a longer one.
&'a mut T is covariant in 'a and invariant in T. You can shrink the borrow itself, but you cannot change the type it points to. That includes lifetimes inside T, as in &mut &'static str.
The failing example
fn assign<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut s: &'static str = "hello";
let local = String::from("temp");
assign(&mut s, &local); // error: `local` does not live long enough
println!("{s}");
}&mut s has type &mut &'static str. Because &mut T is invariant in T, the compiler cannot shrink it to &mut &'a str for a shorter 'a. So 'a must be 'static, and &local cannot be 'static.
Why the rule exists
Suppose the shrink were allowed. assign would write a reference to local into s. When local is dropped, s would still claim to be &'static str and would dangle. Invariance blocks this at the call site.
The fix
Give s a lifetime that is not 'static. Then 'a can be the region where both s and local are alive.
fn assign<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut s: &str = "hello";
let local = String::from("temp");
assign(&mut s, &local);
println!("{s}");
}This compiles because s is never used after local could be dropped. The compiler chooses one 'a for both arguments.
Cell<T> and other interior mutability
Cell<T> lets you replace its contents through a shared reference. That gives the same write access as &mut T, so it has the same restriction.
use std::cell::Cell;
// Does not compile: Cell<&'long str> is invariant in the inner lifetime.
// fn shrink<'long: 'short, 'short>(
// c: &'short Cell<&'long str>,
// ) -> &'short Cell<&'short str> {
// c
// }If this compiled, you could call c.set(...) with a short-lived string through the shrunk view. The original Cell would then hold a dangling reference.
Variance of common types
| Type | Variance in `T` |
|---|---|
| `&'a T` | covariant |
| `&'a mut T` | invariant |
| `Box<T>`, `Vec<T>` | covariant |
| `Cell<T>`, `RefCell<T>` | invariant |
| `*mut T`, `UnsafeCell<T>` | invariant |
The pattern is that a type is covariant when you can only read T through it. It is invariant when you can also write T through it.
Exercise
Why does fn f<'a>(v: &mut Vec<&'a str>, s: &'a str) fail when called with a Vec<&'static str> and a local String borrow, while the same call with a &Vec<&'a str> parameter would be fine for reading?
Show answer
&mut Vec<&'static str> is invariant in the element type, so it cannot shrink to &mut Vec<&'a str>. The 'a is forced to be 'static, which the local borrow cannot satisfy. A shared &Vec<&'static str> is covariant, so it shrinks freely. Pushing a short-lived reference into the static vector would leave a dangling element.