Version: 1.1.0
Operator support
Custom types join arithmetic and comparison by implementing the dunder methods those operators call.
Essentials
__add__and__iadd__back+and+=.__eq__and__ne__back equality.__lt__is enough to derive an ordering when the trait asks for it.- The method must return a new value unless the name starts with
i, which updatesself. - Conform to the matching trait, such as
EquatableorComparable, so generic code can see the operator.
Example
@fieldwise_init
struct Meters(Equatable):
var value: Float64
fn __eq__(self, other: Self) -> Bool:
return self.value == other.value
fn __add__(self, other: Self) -> Self:
return Self(self.value + other.value)
Keep in mind
Keep operators unsurprising. If + would be ambiguous, a named method is the better API.