11# Subtyping and Variance
22
3+ r[ subtype]
4+
5+ r[ subtype.intro]
36Subtyping is implicit and can occur at any stage in type checking or
4- inference. Subtyping is restricted to two cases:
7+ inference.
8+
9+ r[ subtype.kinds]
10+ Subtyping is restricted to two cases:
511variance with respect to lifetimes and between types with higher ranked
612lifetimes. If we were to erase lifetimes from types, then the only subtyping
713would be due to type equality.
@@ -19,6 +25,7 @@ fn bar<'a>() {
1925Since ` 'static ` outlives the lifetime parameter ` 'a ` , ` &'static str ` is a
2026subtype of ` &'a str ` .
2127
28+ r[ subtype.higher-ranked]
2229[ Higher-ranked]   ; [ function pointers] and [ trait objects] have another
2330subtype relation. They are subtypes of types that are given by substitutions of
2431the higher-ranked lifetimes. Some examples:
@@ -39,17 +46,26 @@ let supertype: &for<'c> fn(&'c i32, &'c i32) = subtype;
3946
4047## Variance
4148
49+ r[ subtyping.variance]
50+
51+ r[ subtyping.variance.intro]
4252Variance is a property that generic types have with respect to their arguments.
4353A generic type's * variance* in a parameter is how the subtyping of the
4454parameter affects the subtyping of the type.
4555
56+ r[ subtyping.variance.covariant]
4657* ` F<T> ` is * covariant* over ` T ` if ` T ` being a subtype of ` U ` implies that
4758 ` F<T> ` is a subtype of ` F<U> ` (subtyping "passes through")
59+
60+ r[ subtyping.variance.contravariant]
4861* ` F<T> ` is * contravariant* over ` T ` if ` T ` being a subtype of ` U ` implies that
4962 ` F<U> ` is a subtype of ` F<T> `
63+
64+ r[ subtyping.variance.invariant]
5065* ` F<T> ` is * invariant* over ` T ` otherwise (no subtyping relation can be
5166 derived)
5267
68+ r[ subtyping.variance.builtin-types]
5369Variance of types is automatically determined as follows
5470
5571| Type | Variance in ` 'a ` | Variance in ` T ` |
@@ -65,6 +81,7 @@ Variance of types is automatically determined as follows
6581| ` std::marker::PhantomData<T> ` | | covariant |
6682| ` dyn Trait<T> + 'a ` | covariant | invariant |
6783
84+ r[ subtyping.variance.user-composite-types]
6885The variance of other ` struct ` , ` enum ` , and ` union ` types is decided by
6986looking at the variance of the types of their fields. If the parameter is used
7087in positions with different variances then the parameter is invariant. For
@@ -85,6 +102,7 @@ struct Variance<'a, 'b, 'c, T, U: 'a> {
85102}
86103```
87104
105+ r[ subtyping.variance.builtin-composite-types]
88106When used outside of an ` struct ` , ` enum ` , or ` union ` , the variance for parameters is checked at each location separately.
89107
90108``` rust
0 commit comments