Go by Example

Sorting by Functions

Custom sorting with slices.SortFunc, multi-key sorting with cmp.Compare, and stable vs unstable sort.

A comparison function defines how values are ordered when the default order is not enough. slices.SortFunc expects it to return a negative value, zero, or a positive value when the first value is less than, equivalent to, or greater than the second in that ordering. The comparison must define a strict weak ordering.

Sort people by age, then by name when ages match. cmp.Compare returns the comparison value for each field.

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 every required tie-break field in the comparison function, and keep its comparisons consistent. slices.SortFunc requires a strict weak ordering. Use slices.SortStableFunc when equal values must retain their input order. Stability is not needed just because a sort uses multiple fields.

Enjoyed this? Get more software craft delivered to your inbox.