Mojo trait
Equatable
A type which can be compared for equality with other instances of itself.
The Equatable trait has a default implementation of __eq__() that uses
reflection to compare all fields. This means simple structs can conform to
Equatable without implementing any methods:
@fieldwise_init
struct Point(Equatable):
var x: Int
var y: Int
var p1 = Point(1, 2)
var p2 = Point(1, 2)
print(p1 == p2) # TrueAll fields must conform to Equatable. Override __eq__() for custom
equality semantics.
Note: The default implementation performs memberwise equality comparison. This may not be appropriate for types containing floating-point fields (due to NaN semantics) or types requiring custom equality logic.
Note: The default reflection-based implementation iterates over all fields
at compile time. For mutually recursive types (e.g., struct A has a field
of type List[B] and struct B has a field of type A), this creates an
infinite monomorphization cycle that causes the compiler to hang. To fix
this, provide an explicit __eq__() implementation for at least one type
in the cycle.
Implemented traits
AnyType,
ImplicitlyDestructible
Provided methods
__eq__
__eq__(self: _Self, other: _Self) -> Bool
Define whether two instances of the object are equal to each other.
The default implementation uses reflection to compare all fields for
equality. All fields must conform to Equatable.
Args:
- other (
_Self): Another instance of the same type.
Returns:
Bool: True if the instances are equal according to the type's definition
of equality, False otherwise.
__ne__
__ne__(self: _Self, other: _Self) -> Bool
Define whether two instances of the object are not equal to each other.
Args:
- other (
_Self): Another instance of the same type.
Returns:
Bool: True if the instances are not equal according to the type's
definition of equality, False otherwise.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!