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 updates self.
  • Conform to the matching trait, such as Equatable or Comparable, 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.