Skip to main content
Go’s slices package implements sorting for builtins and user-defined types. This guide covers sorting for built-in types.

Sorting Strings

Sorting functions are generic and work for any ordered built-in type. For a list of ordered types, see cmp.Ordered.
strs := []string{"c", "a", "b"}
slices.Sort(strs)
fmt.Println("Strings:", strs)
// Output: Strings: [a b c]

Sorting Integers

The same Sort function works for integers:
ints := []int{7, 2, 4}
slices.Sort(ints)
fmt.Println("Ints:   ", ints)
// Output: Ints:    [2 4 7]

Checking Sort Order

Use the slices package to check if a slice is already in sorted order:
s := slices.IsSorted(ints)
fmt.Println("Sorted: ", s)
// Output: Sorted:  true

Custom Sorting

Learn how to sort by custom comparison functions

Package Reference

Build docs developers (and LLMs) love