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
__eq__demands that bothmajorandminormatch.__lt__comparesmajorfirst and only falls through tominoron a tie.- That tie-break is why
Version(1, 4)sorts belowVersion(1, 10).
Keywords and builtins used here
IntMovabledefifmainprintreturnselfstructvar
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.
Step 2 of 5 in Operators, step 12 of 22 in Structs & traits.