typestar

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

  1. Comparable is satisfied by __lt__ and __eq__ together.
  2. Both compare the rank field, which is what ordering a card means here.
  3. sort(hand) rearranges the list in place, low rank first.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 5 in Traits, step 20 of 22 in Structs & traits.

← Previous Next →