skip to content

In Rust, why does adding a `Cell<Option<&'a str>>` field to `Arena<'a>` make a call mixing an `Arena<'static>` and a local arena fail with E0597?

level: middleimportance: should knowfreq 20%

answer

  1. a struct inherits variance from its fields
  2. interior mutability through a shared reference
  3. invariance wins every conflict
  4. the annotation forces 'a to be 'static

basics

~20 s

A struct's variance comes from its fields, and Cell<T> is invariant in T, so the new field makes Arena invariant in 'a. rustc can no longer shrink Arena<'static> to the local lifetime, so the local data must live for 'static.

solid answer

~40 s

rustc computes a struct's variance from how its fields use each parameter: all covariant uses give covariance, and any invariant use, or a mix of co- and contravariant uses, makes the parameter **invariant**. `Vec<&'a str>` is covariant, but `Cell<T>` is invariant in `T` because `Cell::set` writes through a shared `&Cell<T>` - if `Arena<'static>` could be viewed as `Arena<'short>`, code holding only `&Arena` could store a short-lived `&str` in a slot still typed `'static`. With the field added, `total(&builtins, &user)` needs one `'a` equal to both arenas' lifetimes; `builtins` is pinned to `'static`, so rustc demands `text` be borrowed for `'static` and reports E0597. Fixes: give the function two lifetime parameters, drop the `'static` annotation, or keep owned data or indices in the `Cell`.

code

rust · 24 lines
rust
use std::cell::Cell;

struct Arena<'a> {
    names: Vec<&'a str>,
    last: Cell<Option<&'a str>>,
}

impl<'a> Arena<'a> {
    fn new(names: Vec<&'a str>) -> Self {
        Arena { names, last: Cell::new(None) }
    }
}

fn total<'a>(a: &Arena<'a>, b: &Arena<'a>) -> usize {
    a.names.len() + b.names.len()
}

fn main() {
    let builtins: Arena<'static> = Arena::new(vec!["core", "std"]);
    let text = String::from("user");
    let user = Arena::new(vec![text.as_str()]);
    println!("{}", total(&builtins, &user));
    builtins.last.set(Some("core"));
}

go deeper

for a junior

Recall that Cell lets you change a value through a shared reference, and that a struct's lifetime behaviour depends on what its fields hold.

for a middle

Explain the inference rule: all covariant uses keep covariance, any invariant use or a co/contra mix makes the parameter invariant. Walk the E0597 back to the 'static annotation.

for a senior

Show the would-be exploit through a shared &Arena and Cell::set, and offer the fixes: separate lifetime parameters, no 'static pin, or indices and owned data in the cell.

for a principal

Treat an interior-mutable field holding a borrow as an API change: it silently makes the type invariant and can break distant callers, so prefer indices or owned data in long-lived types.

## Variance is computed from the fields A struct with a lifetime parameter has a **variance** in that parameter: whether `Arena<'long>` may be used where `Arena<'short>` is expected. You never write it down. rustc infers it from the fields, using the variance of each field type in the parameter: - if every use of `'a` is **covariant**, the struct is covariant in `'a`; - if every use is **contravariant**, the struct is contravariant; - otherwise - any invariant use, or a mix of co- and contravariant uses - the struct is **invariant**. | field type | variance in `'a` | |---|---| | `&'a str`, `Option<&'a str>` | covariant | | `Vec<&'a str>`, `Box<&'a str>` | covariant | | `Cell<Option<&'a str>>`, `RefCell<&'a str>` | invariant | | `&'a mut &'a str` | invariant (the inner use) | | `fn(&'a str)` | contravariant | So a single field changes the whole type. `Arena<'a> { names: Vec<&'a str> }` is covariant; add `last: Cell<Option<&'a str>>` and it becomes invariant, even though `names` did not change. ## Why `Cell<T>` has to be invariant `Cell<T>` is a thin wrapper around `UnsafeCell<T>`, and `UnsafeCell<T>` is invariant in `T` because the compiler treats it specially - it is the one type through which a shared reference may mutate. `Cell::set` takes `&self`. If `Cell<&'static str>` were a subtype of `Cell<&'a str>`, this would be accepted: ```rust fn stash<'a>(arena: &Arena<'a>, s: &'a str) { arena.last.set(Some(s)); } // builtins: Arena<'static> { let tmp = String::from("tmp"); stash(&builtins, &tmp); // view builtins as Arena<'tmp>, store &tmp } // builtins.last.get() would now be a dangling &'static str ``` Invariance is what stops it: `&builtins` can only be an `&Arena<'static>`, so `s` must be `&'static str`, and rustc 1.99.1 rejects the call with E0597 (`tmp` does not live long enough). Every interior-mutability type built on `UnsafeCell` - `RefCell`, `OnceCell`, `Mutex`, `RwLock` - carries the same invariance into any struct that holds it. ## Reading the error rustc prints The diagnostic is not a variance error. Invariance turns into a constraint, `'a` must equal `'static`, and the borrow checker reports the borrow that cannot meet it: 1. `total<'a>(a: &Arena<'a>, b: &Arena<'a>)` asks for one `'a` shared by both arenas; 2. `builtins` is annotated `Arena<'static>` and, being invariant, cannot be viewed at a shorter lifetime, so `'a` is `'static`; 3. `user` must then be `Arena<'static>` too, which means `text.as_str()` must be borrowed for `'static`; 4. `text` is dropped at the end of `main`, so rustc reports `error[E0597]: `text` does not live long enough`, with the label "type annotation requires that `text` is borrowed for `'static`" pointing at the `Arena<'static>` annotation. That label is the clue. When an E0597 points at a type annotation or a far-away `'static`, suspect an invariant field before suspecting the borrow itself. ## Ways out - **Decouple the lifetimes.** `fn total<'a, 'b>(a: &Arena<'a>, b: &Arena<'b>)` no longer requires the arenas to share a lifetime; the call compiles. - **Do not pin the long one.** Writing `let builtins = Arena::new(...)` without `: Arena<'static>` lets inference choose the shorter lifetime for both; the literals still fit. - **Keep borrows out of the cell.** `Cell<Option<usize>>` (an index into `names`) or an owned `String` in a `RefCell` carries no `'a`, so the struct stays covariant. - **Do not reach for `&mut` or `RefCell`.** Both are just as invariant; swapping one for the other changes nothing here. ## Checking a type's variance yourself Variance is never printed by rustdoc or written in the source, but a two-line probe asks the compiler directly. Add a private function that tries to shorten the lifetime: ```rust fn _variance_probe<'s>(a: Arena<'static>) -> Arena<'s> { a } ``` If `Arena` is covariant in `'a`, the probe compiles. If it is invariant, rustc 1.99.1 reports "lifetime may not live long enough" and adds two notes: the type `Arena<'_>` "makes the generic argument `'_` invariant", and "the struct `Arena<'a>` is invariant over the parameter `'a`". Keeping such a probe in a test module turns an accidental variance change into a compile failure in the crate that caused it, instead of in a caller. ## Why it bites in real code Caches and "last seen" slots are added late, to types that already have many callers. The change compiles in the struct's own module and breaks a caller elsewhere that mixed lifetimes, with an error that names a local variable rather than the new field. Knowing that variance is a property of the whole type, recomputed whenever a field changes, turns that puzzle into a one-line diagnosis.

  • Why does rustc report E0597 instead of saying the struct is invariant?
    Variance is not checked as a separate step; it shapes the constraints the borrow checker solves. Invariance turns into "`'a` must equal `'static`", and the first borrow that cannot satisfy it is reported. Some diagnostics, such as E0521, add a note of the form "the struct ... is invariant over the parameter `'a`", but here the label only points at the `Arena<'static>` annotation.
  • Would replacing the `Cell` with a `RefCell` or passing `&mut builtins` make the call compile?
    No. `RefCell<T>` is built on `UnsafeCell<T>` and is invariant in `T` just like `Cell<T>`; rustc 1.99.1 reports the same E0597. Passing `&mut builtins` where `&Arena` is expected only reborrows it as shared, so the invariant `'a` is still forced to `'static`.

  • Variance is declared on the struct, so adding a field cannot change it
  • Cell is invariant because it is !Sync, and every !Sync type is invariant
  • The covariant Vec field outweighs the Cell field, so the struct stays covariant
  • E0597 here means text really is used after it is dropped
  • Switching the Cell to a RefCell makes the struct covariant again