capypad
0 day streak
rust / expert
Snippet

Lifetime Variance and Covariance in References

Variance determines how subtyping between lifetimes affects the compatibility of complex types. Immutable references are covariant over their lifetime, meaning you can pass a longer-lived reference to a function expecting a shorter one. However, mutable references are invariant to prevent memory unsafety where a short-lived reference could be written into a long-lived location.

snippet.rs
rust
1
2
3
4
5
6
7
8
fn subtyping_demo<'a, 'b: 'a>(short: &'a str, long: &'b str) {
// &'b str is a subtype of &'a str because 'b outlives 'a
let x: &'a str = long; // Covariance: we can use a longer lifetime where a shorter is expected
// This would fail if we used mutable references:
// let mut m_long: &'b str = "...";
// let r: &mut &'a str = &mut m_long; // Error: &mut T is invariant over T
}
Breakdown
1
'b: 'a
A lifetime constraint indicating that 'b must last at least as long as 'a.
2
let x: &'a str = long;
Demonstrates covariance: a subtype (&'b) is assigned to a supertype (&'a).
3
&mut T is invariant
Ensures that the exact type T is maintained, preventing invalid lifetime assignments.