What Is Variance in Rust Lifetimes?

Variance in Rust lifetimes defines how generic types relate to their lifetime parameters, allowing the compiler to safely substitute longer lifetimes for shorter ones.

Variance in Rust lifetimes determines how the compiler treats subtyping relationships between generic types based on their lifetime parameters. It dictates whether a type with a longer lifetime can be used where a shorter lifetime is expected (covariant), the opposite (contravariant), or neither (invariant). The compiler automatically calculates this for your types, but you can inspect the result using the #[rustc_dump_variances] attribute on structs, enums, or functions.

#[rustc_dump_variances]
struct Wrapper<'a> {
    data: &'a i32,
}

Compiling this code will output the variance of the 'a parameter (typically Covariant) to the compiler's log, confirming how the type behaves with respect to lifetime subtyping.