sort package
The sort package sorts slices in place. sort.Ints, sort.Strings, and sort.Slice cover most code. sort.Interface is the older, explicit contract with Len, Less, and Swap.
Detailed Explanation
You have a slice of integers or a slice of structs and you need them in order. sort.Ints(ids) sorts []int ascending. sort.Strings(names) does strings. sort.Slice(users, func(i, j int) bool { return users[i].Name < users[j].Name }) takes a less function on indexes. All of these rearrange the caller's slice.
sort.Slice is the default for structs. The less function must be a strict weak order: Less(i, j) and Less(j, i) cannot both be true, and the relation should be transitive. An inconsistent Less can panic or loop inside the sorter. Compare a single key, or a list of keys with if a != b { return a < b }.
Stability. sort.Slice is not stable. Equal elements may change order. sort.SliceStable keeps the relative order of equals. Use stable sort when you sort by last name after already sorting by first name, or when the original order is data.
sort.Interface. A type with Len, Less, Swap can be passed to sort.Sort and sort.Stable. This is how you sort a custom container. For a slice, sort.Slice is less typing and the same algorithm family.
Searching a sorted slice. sort.Search binary-searches a condition func(i int) bool that is false, then true (a suffix). It returns the first true index. sort.SearchInts is a wrapper for []int. The slice must already be sorted in the order the condition assumes.
What it costs. Time is O(n log n). Extra space is small. sort.Slice uses reflection-free swaps on the slice you passed; it is fast enough for ordinary request sizes. For a hot path on []int, sort.Ints is slightly tighter. The slices package (slices.Sort, slices.SortFunc) is the generic, typed successor and is preferred in new Go 1.21+ code.
Code Examples
package main
import (
"fmt"
"sort"
)
type User struct {
Name string
Age int
}
func main() {
ids := []int{3, 1, 2}
sort.Ints(ids)
fmt.Println(ids)
users := []User{{"b", 20}, {"a", 30}}
sort.Slice(users, func(i, j int) bool {
return users[i].Name < users[j].Name
})
fmt.Println(users)
}func firstGE(sorted []int, target int) int {
return sort.Search(len(sorted), func(i int) bool {
return sorted[i] >= target
})
}Common Gotchas
An inconsistent `Less` can crash the sort
do not compare floating NaNs without a rule, and do not swap the meaning of `i` and `j` halfway.
`sort.Slice` is not stable
use `sort.SliceStable` when equal keys must keep order.
`sort.Search` requires a partitioned predicate
if the bool is not a false prefix then a true suffix, the result is meaningless.
Sorting a `nil` or empty slice is a no-op
you do not need a length check first.