typestar

Sorting in Go

Ordering slices with a custom less function.

type Player struct {
    Name  string
    Score int
}

func rank(players []Player) {
    sort.Slice(players, func(i, j int) bool {
        if players[i].Score != players[j].Score {
            return players[i].Score > players[j].Score
        }
        return players[i].Name < players[j].Name
    })
}

func sortNumbers(nums []int) {
    sort.Ints(nums)
}

How it works

  1. sort.Slice takes a less closure over indexes.
  2. Falling through to a second field breaks ties.
  3. sort.Ints handles the simple numeric case.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
301
Tokens
96
Three-star pace
105 tpm

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

Type this snippet

Step 3 of 5 in Collections & text, step 11 of 26 in Standard library & project layout.

← Previous Next →