Sorting
| Sort ints and strings | |
| Sort structs with Less | |
| SortFunc and Find | |
| The slices package |
Sort ints and strings
The sort package sorts slices in place, so the call changes the slice instead of returning a copy. Ints orders numbers from small to large, and Strings orders text in byte order.
AreSorted helpers check the order without touching the data. They are handy in tests and in code that must confirm input before running an algorithm that needs sorted data.
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{5, 3, 8, 1}
sort.Ints(nums)
fmt.Println(nums)
names := []string{"go", "c", "python"}
sort.Strings(names)
fmt.Println(names)
fmt.Println(sort.IntsAreSorted(nums))
}
[1 3 5 8]
[c go python]
true
Sort structs with Less
Custom types need three methods to join the sort.Interface family: Len, Less, and Swap. Less carries the ordering rule, while Len and Swap are plain plumbing around the slice.
The example below sorts users by age. The byAge type wraps a user slice, so the original user type stays clean and the ordering rule lives in one small place.
package main
import (
"fmt"
"sort"
)
type user struct {
name string
age int
}
type byAge []user
func (a byAge) Len() int {
return len(a)
}
func (a byAge) Less(i, j int) bool {
return a[i].age < a[j].age
}
func (a byAge) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func main() {
team := []user{{"Ann", 30}, {"Bob", 20}}
sort.Sort(byAge(team))
fmt.Println(team)
}
[{Bob 20} {Ann 30}]
SortFunc and Find
When a full method set feels heavy, sort.Slice takes the slice plus a small Less function. The closure sees the slice, so the rule stays next to the call that needs it.
sort.Search finds a position inside sorted data with binary search. Give it the length and a function that reports whether the element at an index is large enough, and it returns the first matching index.
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{5, 3, 8, 1}
sort.Slice(nums, func(i, j int) bool {
return nums[i] < nums[j]
})
fmt.Println(nums)
at := sort.Search(len(nums), func(i int) bool {
return nums[i] >= 5
})
fmt.Println(at)
}
[1 3 5 8]
2
The slices package
Since Go 1.21 the slices package offers generic helpers that cover the common cases. Sort replaces Ints and Strings with one function, and helpers such as Contains and IsSorted answer frequent questions in one call.
New code should reach for slices first and fall back to sort only for custom orderings that need an explicit Less function or a stable sort with extra control.
package main
import (
"fmt"
"slices"
)
func main() {
nums := []int{5, 3, 8, 1}
slices.Sort(nums)
fmt.Println(nums)
fmt.Println(slices.Contains(nums, 3))
fmt.Println(slices.IsSorted(nums))
}
[1 3 5 8]
true
true
Next: Concurrency patterns
Article author: Arthur Isaev