Sorting your own struct in Mojo
Conform to Comparable and the standard sort will order your values.
from std.builtin.sort import sort
@fieldwise_init
struct Card(ImplicitlyCopyable, Movable, Comparable):
var rank: Int
def __lt__(self, other: Self) -> Bool:
return self.rank < other.rank
def __eq__(self, other: Self) -> Bool:
return self.rank == other.rank
def main():
var hand = [Card(7), Card(2), Card(10), Card(5)]
sort(hand)
for card in hand:
print(card.rank)
How it works
Comparableis satisfied by__lt__and__eq__together.- Both compare the
rankfield, which is what ordering a card means here. sort(hand)rearranges the list in place, low rank first.
Keywords and builtins used here
IntMovabledefformainprintreturnselfstructvar
The run, in numbers
- Lines
- 19
- Characters to type
- 369
- Tokens
- 102
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 87 seconds.
Step 5 of 5 in Traits, step 20 of 22 in Structs & traits.