In Rust, why does `overwrite(&mut label, &input)` fail with E0597 when `label: &'static str` and `overwrite` takes `&mut &'a str` and `&'a str`?
answer
- what could be written through it
- a slot typed 'static
- &'a mut T and its T
- type annotation requires a 'static borrow
basics
~20 s&mut T is invariant in T, so &mut &'static str cannot be treated as &mut &'a str. That forces 'a to 'static, so the borrow of input must last for 'static and rustc rejects it; otherwise label would dangle once input drops.
solid answer
~40 s`&'a mut T` is covariant in `'a` but **invariant** in `T`. Here `T` is `&'static str`, and because no subtyping may be applied under the `&mut`, `overwrite`'s `'a` must be exactly `'static`, so the second argument must be `&'static str` too. `&input` is a borrow of a local `String`, so rustc 1.99.1 reports E0597 with the label "type annotation requires that `input` is borrowed for `'static`". If `&mut T` were covariant, rustc could view `label` as `&mut &'short str`, `overwrite` would store `&input` in it, and after `input` dropped, `label` would be a dangling `&'static str` - a use-after-free in safe code. The fix is to drop the `'static` annotation and keep `label`'s uses inside `input`'s scope, or store an owned `String`.
code
rust · 12 linesfn overwrite<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut label: &'static str = "default";
{
let input = String::from("from-request");
overwrite(&mut label, &input);
}
println!("{label}");
}go deeper
Recall that &mut gives write access, and that writing a short-lived reference into a slot typed 'static would leave a dangling reference once the source is dropped.
Explain variance of &'a mut T: covariant in 'a, invariant in T. Trace how invariance forces 'a to 'static and why the error label points at the annotation.
Walk the five-step use-after-free that covariance would allow, contrast Box and Vec covariance by ownership, and offer fixes: no 'static pin, reorder declarations, or own the data.
Use this as the canonical argument for why mutable access must fix types exactly; review E0597s that point at distant annotations as invariance, not as misplaced scopes.
## The code and what rustc prints `fn overwrite<'a>(slot: &mut &'a str, value: &'a str) { *slot = value; }` is a perfectly reasonable function: it writes a `&'a str` into a slot of type `&'a str`. The caller is the problem: ```rust let mut label: &'static str = "default"; { let input = String::from("from-request"); overwrite(&mut label, &input); } println!("{label}"); ``` rustc 1.99.1 rejects it with `error[E0597]: `input` does not live long enough`, and the label under `&'static str` reads "type annotation requires that `input` is borrowed for `'static`". Deleting the final `println!` does not help: the annotation alone fixes `label`'s type, so the same E0597 appears. ## Why covariance here would be a use-after-free Suppose `&mut T` were covariant in `T`, as `&T` is. Then: 1. `&mut label` has type `&mut &'static str`; 2. covariance would let rustc view it as `&mut &'input str`, where `'input` is the short life of the `String`; 3. `overwrite` writes `&input` into the slot - legal at that type; 4. `input` is dropped at the end of the block; 5. `label` is still typed `&'static str`, but now points at freed memory, and the `println!` reads it. Nothing in `overwrite` is wrong. The unsoundness would come from forgetting, behind a mutable reference, that the slot's owner still believes the stronger type. A `&mut` gives both read and write access to the pointee, and a write must respect the type the *owner* holds, so the pointee type must be exactly the same on both sides. That is **invariance**: no subtyping relation between `T` and `U` carries over to `&mut T` and `&mut U`. ## The full variance of `&'a mut T` | position | variance | why it is safe | |---|---|---| | `'a`, the borrow's own lifetime | covariant | using a borrow for less time than allowed never lets anything dangle | | `T`, the pointee type | invariant | writes go through it, so the pointee type must not change | Compare `&'a T`: covariant in both, because a shared reference cannot write, so reading a `&'static str` as a `&'short str` loses nothing that matters. Owning containers behave like `&T`, not like `&mut T`: `Box<T>` and `Vec<T>` are covariant in `T`. That is sound because a move transfers the only path to the value. Once `Box<&'static str>` has been moved into a variable typed `Box<&'b str>`, nothing remains that remembers the longer type. Put that `Vec` behind a `&mut`, though, and invariance returns: passing `&mut names` (a `&mut Vec<&'static str>`) to `fn add<'a>(v: &mut Vec<&'a str>, s: &'a str)` with a local `&t` fails with the same E0597. ## Fixes - **Do not pin the slot to `'static`.** With `let mut label = "default";` and every use of `label` inside `input`'s block, rustc infers a shorter type for `label` and the call compiles. - **Make the source outlive the slot.** Declare `input` before an unannotated `label`, so `&input` is valid for every use of `label`, including a `println!` at the end. - **Store owned data.** If the slot must outlive the request, make it a `String` (or `Cow<'static, str>`) and copy into it. - **Do not try to widen with a cast.** No `as` cast can lengthen a reference's lifetime, and `mem::transmute` would only reintroduce the use-after-free the compiler just prevented. ## Spotting it in a review The tell is an E0597 whose label points at a `'static` annotation or a field type a long way from the failing line. Look for a `&mut` - or a `Cell`, `RefCell` or `Mutex` - wrapping a type that contains the lifetime: those positions are invariant, and invariance makes the longest lifetime in the expression win. The same rule reaches standard functions that take two `&mut T`: `std::mem::swap(&mut label, &mut short)` with `label: &'static str` and `short` borrowing a local fails with the same E0597, because both arguments must share one exact `T`.
- If `&mut T` must be invariant in `T`, why is `&'a mut T` still covariant in `'a`?Shortening `'a` only limits how long the mutable borrow may be used; it does not change what may be written through it. Using an exclusive borrow for less time than allowed cannot leave anything dangling, so rustc lets `&'long mut T` stand in for `&'short mut T` while keeping `T` fixed.
- Why is `Box<&'static str>` allowed to become `Box<&'b str>` when `&mut &'static str` is not?A `Box` is owned. Converting it means moving it, and the move destroys the only path that knew the content was `'static`, so nothing can later read the weaker value at the stronger type. A `&mut` leaves the owner alive and still typed `&'static str`, so a write through the weaker view would break the owner's type.
- Does deleting the later `println!("{label}")` make the original code compile?No. Non-lexical lifetimes shorten borrows, not declared types. `label: &'static str` fixes the pointee type, invariance forces `overwrite`'s `'a` to `'static`, and `&input` still has to live for `'static`; rustc 1.99.1 reports the same E0597. Removing the annotation is what lets inference pick a shorter type.
- &mut T is covariant in T exactly like &T, only with mutation allowed
- overwrite is unsound and should be rewritten; the caller is fine
- Non-lexical lifetimes make it compile once label is never read again
- &'a mut T is invariant in 'a as well as in T
- An as cast to &'static str would fix the error safely