Understanding Lifetime Variance in Rust: Covariance, Invariance, and Contravariance
Rust's type system uses variance to describe how generic and lifetime parameters relate to each other in a type hierarchy, determining when one type can substitute for another. Covariance allows a type to be replaced by a subtype, such as a longer-lived 'static reference standing in for a shorter-lived 'a reference. Invariance requires an exact type match, as seen with mutable references, where no substitution in either direction is permitted. Contravariance works in the opposite direction, meaning a function accepting a broader lifetime parameter is considered more useful than one with stricter requirements. These three variance rules govern safe substitution throughout Rust programs, and understanding them is essential for writing correct code involving complex lifetime annotations.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in