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
sort.Slicetakes a less closure over indexes.- Falling through to a second field breaks ties.
sort.Intshandles the simple numeric case.
Keywords and builtins used here
boolfuncifintreturnstringstructtype
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.
Step 3 of 5 in Collections & text, step 11 of 26 in Standard library & project layout.