As of Go 1.8+ you can now use sort.Slice
to sort a slice:
1
2
3
sort.Slice(planets, func(i, j int) bool {
return planets[i].Axis < planets[j].Axis
})
There is normally no reason to use an array instead of a slice, but in your example you are using an array, so you have to overlay it with a slice (add [:]
) to make it work with sort.Slice
:
1
2
3
sort.Slice(planets[:], func(i, j int) bool {
return planets[i].Axis < planets[j].Axis
})
The sorting changes the array, so if you really want you can continue to use the array instead of the slice after the sorting.
1
2
3
4
5
6
type Planet struct {
Name string `json:"name"`
Axis int64 `json:"Axis"`
}
planets := [...]Planet{{"a", 12}, {"b", 9}, {"c", 20}}
Slices.Sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main
import (
"fmt"
"slices"
)
func main() {
strs := []string{"c", "a", "b"}
slices.Sort(strs)
fmt.Println("Strings:", strs)
ints := []int{7, 2, 4}
slices.Sort(ints)
fmt.Println("Ints: ", ints)
s := slices.IsSorted(ints)
fmt.Println("Sorted: ", s)
}