×

go · level 2 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

sorts anything, using a rule you write.

sort.Ints(scores) puts whole numbers smallest first, and sort.Strings does A to Z. But how should Go sort a slice of players: by name, by score, by age? Only you know, so you hand over the rule.

sort.Slice(players, func(i, j int) bool { ... }) takes the slice and a : a function with no name, written right there. Go calls it many times, and it answers one question: should item i come before item j?

To put the highest score first, return players[i].Score > players[j].Score. For a tie-breaker, compare the scores first and, only when they are equal, compare the names instead.

package main
import "fmt"
import "sort"
type Player struct {
	Name  string
	Score int
}
func main() {
	players := []Player{{Name: "Ava", Score: 30}, {Name: "Leo", Score: 45}, {Name: "Sam", Score: 30}, {Name: "Zoe", Score: 12}}
	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
	})
	for _, p := range players {
		fmt.Println(p.Name, p.Score)
	}
}

Using < on two strings compares them in dictionary order, so "Ava" < "Sam" is true.