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

Create a free account to save this page, take notes and track your progress. Sign in

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

ParameterDescription
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

Example 1
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.

Sort by age descending, then name
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

VersionChange
Go 1.21Added

Was this page helpful?