Go 1.27 reference · Slices, Maps, Iterators and JSON
Go slices.Sort and slices.SortFunc Function
Sort a slice in place in ascending order, or with a comparison function for custom and multi-key ordering.
Go 1.27 Since 1.21
Syntax
func Sort[S ~[]E, E cmp.Ordered](x S) func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int)
Parameters
| Parameter | Description |
|---|---|
x |
The slice to sort in place. |
cmp(a, b) |
Negative if a < b, zero if equal, positive if a > b (cmp.Compare helps). |
SortStableFunc |
Keeps the order of equal elements. |
Examples
package main
import (
"fmt"
"slices"
)
func main() {
nums := []int{5, 2, 9, 1}
slices.Sort(nums)
fmt.Println(nums)
names := []string{"pear", "Apple", "fig"}
slices.Sort(names)
fmt.Println(names)
}
Output
[1 2 5 9] [Apple fig pear]
Run this on your computer — see “Get Started” for setup.
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
type User struct {
Name string
Age int
}
users := []User{{"ana", 31}, {"ben", 25}, {"cy", 31}}
slices.SortFunc(users, func(a, b User) int {
return cmp.Or(cmp.Compare(b.Age, a.Age), cmp.Compare(a.Name, b.Name))
})
fmt.Println(users)
}
Output
[{ana 31} {cy 31} {ben 25}]Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Go 1.21 | Added |
Related
slices.Contains, Index and BinarySearch· Search slices: check membership, find an index, or binary-search a sorted slice.maps.Keys and slices.Sorted· Iterate a map's keys or values; combine with slices.Sorted for a deterministic order, since map iteration is random.- Go Arrays and Slices · tutorial