Sorting by Functions
Custom sorting with slices.SortFunc, multi-key sorting with cmp.Compare, and stable vs unstable sort.
A comparison function defines which of two values should come first when the default order is not enough. slices.SortFunc expects a negative number if the first comes first, zero if they are equal for this order, and a positive number if the second comes first. Make sure the rule gives consistent results.
Sort people by age, then by name when ages match. cmp.Compare returns a negative number, zero or a positive number to show which value comes first.
package main
import (
"cmp"
"fmt"
"slices"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{{"Ada", 36}, {"Lin", 28}, {"Sam", 28}}
slices.SortFunc(people, func(a, b Person) int {
if order := cmp.Compare(a.Age, b.Age); order != 0 {
return order
}
return cmp.Compare(a.Name, b.Name)
})
fmt.Println(people)
}In production
Include each tie-break field in the comparison. Use slices.SortStableFunc when values that compare as equal must keep their original order. A stable sort is not required just because the comparison uses several fields.