sort

Guided tour · Collections · pkg.go.dev →

Sorting for slices and any sort.Interface. For generic slice sorting prefer the newer slices package.

sort.Slice — the everyday case

Sort with a less func

people := []struct{ Name string; Age int }{
    {"Ada", 36}, {"Alan", 41}, {"Grace", 85},
}
sort.Slice(people, func(i, j int) bool {
    return people[i].Age < people[j].Age
})
fmt.Println(people)
Output
[{Ada 36} {Alan 41} {Grace 85}]

SliceStable — preserves order of equals

Use when you sort on a secondary key and want the primary key's relative order preserved.

sort.SliceStable(data, func(i, j int) bool {
    return data[i].Priority < data[j].Priority
})

Built-in helpers for common slice types

Ints, Strings, Float64s

nums := []int{3, 1, 4, 1, 5, 9}
sort.Ints(nums)
fmt.Println(nums)                     // [1 1 3 4 5 9]
fmt.Println(sort.IntsAreSorted(nums)) // true
Output
[1 1 3 4 5 9]
true

sort.Interface — when you need full control

For non-slice types or multi-key sorts too complex for sort.Slice. Implement Len, Less, Swap.

Minimal custom type

type byLen []string
func (b byLen) Len() int           { return len(b) }
func (b byLen) Less(i, j int) bool { return len(b[i]) < len(b[j]) }
func (b byLen) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }

words := []string{"banana", "fig", "apple"}
sort.Sort(byLen(words))
fmt.Println(words)
Output
[fig apple banana]