go · level 2 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Which way round? Guess the order.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
import "sort"
func main() {
ages := []int{9, 3, 12, 7}
sort.Slice(ages, func(i, j int) bool {
return ages[i] > ages[j]
})
fmt.Println(ages)
}
your turn
Your turn. Tidy the bookshelf.
Choose how to sort the shelf: by Title or by Pages, with < or >. Use the same field on both sides of the comparison, then run it.
output
press run to see what happens
fix it
The class register refuses to sort. Fix it!
output
press run to see what happens
- Nothing moved at all. Read the rule on line 7 carefully, letter by letter.
- The rule compares
names[i]with itself, so it can never betrue. - Change the second names[i] on line 7 to names[j], then run.
nailed it
you can sort anything your way. :D
sort.Intsandsort.Stringssort smallest first or A to Z.sort.Slicetakes a function literal that compares itemsiandj.- Return
truewhen itemishould come first.
new words in your collection
- sort.Slice
- function literal
This lesson isn’t saved. A free account remembers every lesson you finish.