Sorting
Sort slices of ordered values in place; choose stable or custom sorting when comparison rules require it.
The slices package sorts a slice in place, which means it changes the original slice. slices.Sort orders values that have an obvious order, such as numbers from low to high or words alphabetically. 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 does not promise to keep equal values in their original order. A stable sort keeps that order. Use slices.SortStableFunc when it matters, or slices.SortFunc when values need a custom rule for which one comes first.
Enjoyed this? Get more software craft delivered to your inbox.