Sorting
Sort slices of ordered values in place; choose stable or custom sorting when comparison rules require it.
The slices package sorts slices in place. slices.Sort orders values that already have a natural order, such as numbers and strings. These functions require Go 1.21 or later.
Sort changes the order of values in the original slice.
package main
import (
"fmt"
"slices"
)
func main() {
numbers := []int{3, 1, 4, 2}
slices.Sort(numbers)
fmt.Println(numbers)
}In production
slices.Sort is not stable, so equal elements may change relative order. Use slices.SortStableFunc when that order must be preserved, or slices.SortFunc when values need a custom comparison.
Enjoyed this? Get more software craft delivered to your inbox.