All types with generic parameters have a variance with respect to those parameters.

In Rust lifetimes form a subtype relationship: 'static is a subtype of 'a because it is valid for longer.

Key variance rules:

  • &'a T is covariant in both 'a and T: you can provide &'static T where &'a T is expected
  • &mut T is invariant in T: you must provide exactly T, not a subtype or supertype
  • function arguments are contravariant — a function that accepts a longer-lived reference can be used where a shorter-lived one is expected

See also

References

  • J. Gjengset, Rust for Rustaceans: Idiomatic Programming for Experienced Developers. No Starch Press, 2021.