pub trait CompareTypes<Rhs = Self> {
// Required method
fn compare_types(&self, other: &Rhs) -> Option<TypeRelation>;
// Provided methods
fn is_subtype_of(&self, other: &Rhs) -> bool { ... }
fn is_supertype_of(&self, other: &Rhs) -> bool { ... }
fn is_any(&self) -> bool { ... }
fn is_assignable_to(&self, dst: &Rhs) -> bool { ... }
}Expand description
Trait for comparisons corresponding to subtyping relations.
<: and :> are used to mean “is subtype of” and “is supertype of” respectively.
<<: and :>> are used as their “strict” counterparts (no equality).
Implementations must be:
- Transitive: if
a <: bandb <: c, thena <: c - Dual: if
a <: b, thenb :> a - Antisymmetric:
- if
a <<: b, thenb <<: acan’t be true - if
a <: bandb <: a, thena == b
- if
Output of Self::is_subtype_of and Self::is_supertype_of must be consistent with
Self::compare_types
The Rhs type parameter is to allow comparing the runtime type of a value with static types,
without going through intermediate steps.
Instead of Value::get_type(&val).compare_types(&ty), which might require allocations for the
intermediate Type, one can use Value::compare_types(&val, &ty)
Required Methods§
Sourcefn compare_types(&self, other: &Rhs) -> Option<TypeRelation>
fn compare_types(&self, other: &Rhs) -> Option<TypeRelation>
Compares types and returns their relation with regards to subtyping.
- Returns
Someif types are equal, or one type is a subtype of the other. - Returns
Noneif neither type is equal to or is subtype of the other.
Provided Methods§
Sourcefn is_subtype_of(&self, other: &Rhs) -> bool
fn is_subtype_of(&self, other: &Rhs) -> bool
Returns true if self is equal to or is a strict subtype of other
Converse of Self::is_supertype_of
Sourcefn is_supertype_of(&self, other: &Rhs) -> bool
fn is_supertype_of(&self, other: &Rhs) -> bool
Returns true if self is equal to or is a strict supertype of other
Converse of Self::is_subtype_of
Sourcefn is_any(&self) -> bool
fn is_any(&self) -> bool
Allows having an “escape hatch”.
Due to not having separate top and bottom types, and treating any as both, we need to be
especially lax in some situations to keep things convenient and backwards compatible.
We can’t treat any as a bottom type in CompareTypes::compare_types as due to
reflexivity it would imply all types are subtypes of all other types:
anyas top type:int <: anyanyas bottom type:any <: listint <: list???
Sourcefn is_assignable_to(&self, dst: &Rhs) -> bool
fn is_assignable_to(&self, dst: &Rhs) -> bool
Equivalent to CompareTypes::is_subtype_of by default.
Exists as a separate method to allow relaxing requirements when needed.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".