typestar

Equality and ordering in Mojo

__eq__ and __lt__ teach a struct how to answer == and <.

@fieldwise_init
struct Version(ImplicitlyCopyable, Movable):
    var major: Int
    var minor: Int

    def __eq__(self, other: Self) -> Bool:
        return self.major == other.major and self.minor == other.minor

    def __lt__(self, other: Self) -> Bool:
        if self.major != other.major:
            return self.major < other.major
        return self.minor < other.minor


def main():
    var old = Version(1, 4)
    var new = Version(1, 10)
    print(old == new, old < new)

How it works

  1. __eq__ demands that both major and minor match.
  2. __lt__ compares major first and only falls through to minor on a tie.
  3. That tie-break is why Version(1, 4) sorts below Version(1, 10).

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
419
Tokens
114
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 86 seconds.

Type this snippet

Step 2 of 5 in Operators, step 12 of 22 in Structs & traits.

← Previous Next →