← ClaudeAtlas

rust-variancelisted

Use when a lifetime coercion is refused and you must decide whether a type constructor is covariant, contravariant, or invariant, or when you add a lifetime parameter to a public type. Covers the three one-line probes that settle any variance question in one rustc run, the variance of &T, &mut T, *const T, *mut T, Box, Vec, fn(T), fn() -> T, Cell, Mutex, dyn Trait and every PhantomData form, why traits match their parameters and associated types by equality so a fn item returning &'static str fails resize_with with E0597, the three fixes for a producer whose output lives too long, unbounded lifetimes from a raw-pointer deref, and why adding interior mutability to a published struct is a breaking change. Triggers on "variance", "covariant", "contravariant", "subtyping", "lifetime may not live long enough" on a coercion, "is invariant over the parameter", "borrowed for 'static", "resize_with", "unbounded lifetime", "phantomdata variance", "dyn fn lifetime", "&mut is invariant", or "sender is invariant".
po4yka/rust-skills · ★ 2 · AI & Automation · score 76
Install: claude install-skill po4yka/rust-skills
# Rust variance ## Purpose This skill answers one question: does a value that holds `'b` fit where the compiler asks for `'a`, given `'b: 'a`. The answer comes from the type constructor around the lifetime, not from the lifetime. Do not get this sentence wrong: **variance belongs to type constructors only.** A trait matches its parameters and its associated types by equality, so nothing coerces through a trait bound. A named function *item* that returns `&'static str` therefore does not satisfy `F: FnMut() -> &'a str`. Its `fn` pointer type does satisfy it, because the pointer type itself subtypes. See fix 3 below. Every diagnostic below is copied from rustc 1.97.0, edition 2024, aarch64-apple-darwin. Raw-pointer soundness belongs to `rust-unsafe`. Reading E0597 and E0521 in general belongs to `rust-compiler-errors`. This skill covers only the coercion decision. ## Route the symptom to a section | Symptom or task | Section | | --- | --- | | You must know the variance of a type you own | [Settle it with a probe](#settle-it-with-a-probe) | | `note: the struct X<T> is invariant over the parameter T` | [The variance table](#the-variance-table) | | `note: mutable references are invariant over their type parameter` | [Settle it with a probe](#settle-it-with-a-probe) | | `note: requirement that the value outlives 'static introduced here`, pointing at a trait bound | [Traits match by equality](#traits-match-their-parameters-by-equality) | | `error[E0597]` at `resize_with`, `ma