Go📦Standard Libraryintermediate
sort and slices — Sorting
Go · Standard Library · Run with go run
Explanation
The `sort` package sorts slices and user-defined collections. `sort.Ints`, `sort.Strings`, and `sort.Float64s` handle the common cases; `sort.Slice` sorts any slice with a custom less-function. Since Go 1.21 the generic `slices` package adds `slices.Sort`, `slices.SortFunc`, and `slices.BinarySearch` — type-safe and usually preferred in modern code.
Real-World Scenario
An API returns a list of products that must be displayed cheapest-first, then alphabetically for ties. `slices.SortFunc(products, func(a, b Product) int { ... })` expresses the multi-key comparison in one place.
Quick Snippet
snippet.go
import (
"sort"
"slices"
)
nums := []int{3, 1, 4, 1, 5, 9}
sort.Ints(nums) // [1 1 3 4 5 9]
// Custom comparison with sort.Slice
people := []Person{{"Bob", 30}, {"Al", 25}}
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
// Modern generic API (Go 1.21+)
slices.Sort(nums)
slices.SortFunc(people, func(a, b Person) int {
return a.Age - b.Age
})Full Example
sort_pkg.go
// Compile: go run sort_pkg.go
// Output:
// sorted ints: [1 1 3 4 5 9]
// by age: [{Al 25} {Bob 30}]
// slices.Sort: [1 1 3 4 5 9]
package main
import (
"fmt"
"slices"
"sort"
)
type Person struct {
Name string
Age int
}
func main() {
nums := []int{3, 1, 4, 1, 5, 9}
sort.Ints(nums)
fmt.Println("sorted ints:", nums)
people := []Person{{"Bob", 30}, {"Al", 25}}
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
fmt.Println("by age:", people)
// Modern generic API (Go 1.21+)
more := []int{9, 5, 1, 4, 1, 3}
slices.Sort(more)
fmt.Println("slices.Sort:", more)
}
Run command
go run sort_pkg.go