Skip to main content

CompareTypes

Trait CompareTypes 

Source
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 <: b and b <: c, then a <: c
  • Dual: if a <: b, then b :> a
  • Antisymmetric:
    • if a <<: b, then b <<: a can’t be true
    • if a <: b and b <: a, then a == b

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§

Source

fn compare_types(&self, other: &Rhs) -> Option<TypeRelation>

Compares types and returns their relation with regards to subtyping.

  • Returns Some if types are equal, or one type is a subtype of the other.
  • Returns None if neither type is equal to or is subtype of the other.

Provided Methods§

Source

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

Source

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

Source

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:

  • any as top type: int <: any
  • any as bottom type: any <: list
  • int <: list???
Source

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".

Implementors§