How to Sort a Slice in Go
Created
Modified
Using Slice Function
You simply pass an anonymous function to the sort.Slice function:
package main
import (
"fmt"
"sort"
)
func main() {
s := []string{"Houston", "Atlanta", "Boston"}
sort.Slice(s, func(i, j int) bool {
return s[i] < s[j]
})
fmt.Println(s)
a := []int{6, 4, 2}
sort.Slice(a, func(i, j int) bool {
return a[i] < a[j]
})
fmt.Println(a)
}
[Atlanta Boston Houston] [2 4 6]
Slice sorts the slice x given the provided less function. It panics if x is not a slice.
See the following example:
package main
import (
"fmt"
"sort"
)
func main() {
people := []struct {
Name string
Age int
}{
{"Gopher", 7},
{"Alice", 55},
{"Vera", 24},
{"Bob", 75},
}
sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
fmt.Println("By name:", people)
sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println("By age:", people)
}
By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}] By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]