Sub topic 5
Invariance: why &mut T and Cell<T> cannot shrink
This chapter assumes you know ownership and borrowing, basic lifetime annotations, and generics. It also assumes you have read the earlier chapters on lifetime subtyping and covariance. There, you saw that &'long T can be used where &'short T is expected. Here you will see where that substitution is forbidden, and why the borrow checker needs the ban.
The rule in one sentence
A type is invariant in a parameter when the compiler requires that parameter to match exactly. The longer lifetime cannot stand in for a shorter one, and the shorter cannot stand in for a longer one.
&'a mut T is covariant in 'a and invariant in T. Both parts matter:
- The borrow itself can still shrink. You can pass a
&'long mut Vec<i32>where a&'short mut Vec<i32>is expected. This is what reborrowing does. - Whatever
Tcontains cannot shrink. IfTis&'static str, you cannot treat&mut &'static stras&mut &'a str.
| Type | Variance in `'a` | Variance in `T` |
|---|---|---|
| `&'a T` | covariant | covariant |
| `&'a mut T` | covariant | invariant |
| `Box<T>`, `Vec<T>` | n/a | covariant |
| `Cell<T>`, `RefCell<T>`, `UnsafeCell<T>` | n/a | invariant |
| `*mut T` | n/a | invariant |
| `*const T` | n/a | covariant |
The failing example
This program does not compile:
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}");
}The variable s is declared as &'static str, so &mut s has type &mut &'static str. The signature of assign ties both arguments to one lifetime 'a. If &mut &'static str were covariant in the inner lifetime, the compiler could shrink it to &mut &'a str for some short 'a. It could then borrow local for that same short 'a. The call would store a reference to local inside s.
Then local is dropped. The variable s still claims to be &'static str, so println! would read freed memory.
Invariance blocks this. The type &mut &'static str cannot become &mut &'a str for any 'a other than 'static. The call therefore forces 'a = 'static, which requires &local to be 'static. It is not, so the compiler reports an error on local.
The fix is in the annotation
The scope of local is not the problem. It lives until the end of main in both versions. The 'static annotation on s is the problem. Remove it and the compiler infers a lifetime that fits:
fn assign<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut s = "hello";
let local = String::from("temp");
assign(&mut s, &local);
println!("{s}");
}Here s starts as &'x str with 'x chosen by inference. The literal "hello" is &'static str, and it is copied into s by a covariant coercion at the let. After that, 'x stays fixed, and the compiler picks one that &local also satisfies.
Why mutation forces invariance
Think of a type parameter as a position where values flow.
- Reading out. If you only read a
Tfrom a container, a longer-livedTis a safe substitute for a shorter-lived one. This direction gives covariance. Shared references,Box<T>andVec<T>behave this way. - Writing in. If you only write a
Tinto a place, the place must accept at least the lifetimes callers will write. A place that accepts short-lived values can safely hold long-lived ones. This direction gives contravariance, which the next chapter covers. - Both.
&mut Tlets you read aTand write aT. Reading demands thatTmay shrink, and writing demands that it may grow. The only type satisfying both is the exact one. That is invariance.
Cell<T>: mutation through a shared reference
&T is covariant in T. That is safe for ordinary types because a shared reference cannot change what it points to. Cell<T> breaks this assumption. Cell::set takes &self, so it writes through a shared reference. If Cell<T> were covariant, you could shrink &Cell<&'static str> to &Cell<&'a str> and set a short-lived reference into it. That is the same attack as before.
So Cell<T> is invariant in T. So are RefCell<T>, Mutex<T> and UnsafeCell<T>, which is the primitive underneath them. Any type that contains one of these in a field inherits the invariance.
This does not compile:
use std::cell::Cell;
fn store<'a>(slot: &Cell<&'a str>, value: &'a str) {
slot.set(value);
}
fn main() {
let cell: Cell<&'static str> = Cell::new("start");
let owned = String::from("later");
store(&cell, &owned); // error: `owned` does not live long enough
println!("{}", cell.get());
}The explicit Cell<&'static str> pins the lifetime, as &'static str did before. Change the declaration to let cell = Cell::new("start"); and the program compiles. The compiler then infers a lifetime for the cell that &owned also satisfies.
A practical consequence: `&'a mut Foo<'a>`
Invariance causes a well-known trap. Suppose a struct is invariant in its lifetime because it holds a Cell, and a method borrows it for that same lifetime:
use std::cell::Cell;
struct Counter<'a> {
label: Cell<&'a str>,
n: u32,
}
impl<'a> Counter<'a> {
fn bump(&'a mut self) {
self.n += 1;
}
}
fn main() {
let mut c = Counter { label: Cell::new("x"), n: 0 };
c.bump();
c.bump(); // error: cannot borrow `c` as mutable more than once at a time
}The method takes &'a mut Counter<'a>. Because Counter<'a> is invariant, the compiler cannot shrink the inner 'a to match a short borrow. The borrow must therefore last as long as 'a, which spans every later use of c. The first borrow never ends, and the second call conflicts with it.
If Counter were covariant in 'a, the compiler could shrink the inner lifetime and this code would compile. The fix is to write fn bump(&mut self). That gives the borrow its own anonymous lifetime, unrelated to 'a.
Quick checklist
- Does the type contain
&mut T,Cell<T>,RefCell<T>,*mut TorUnsafeCell<T>, with the lifetime insideT? Then it is invariant in that lifetime. - Is an annotation like
&'static stron a local variable fixing the lifetime? Remove it and let inference choose. - Does an error say "borrowed for
'static" or "requires that ... is borrowed for'a"? Look for a&mutorCellwrapping the lifetime.
Exercise
In fn f<'a>(x: &mut &'a str, y: &'a str), why can a caller pass &mut s where s: &'static str only if y is also 'static? Would fn g<'a>(x: &&'a str, y: &'a str) have the same restriction?
Show answer
&mut &'static str is invariant in the inner lifetime, so 'a must equal 'static, and y must therefore be 'static. The restriction exists because f could write y into *x. In g the type &&'static str is covariant in the inner lifetime, so the compiler can shrink it to &&'a str for a short 'a. y can then be any reference that lives at least as long as 'a. g has no restriction, and it cannot write through x anyway.