sorting排序
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)
}
Sorting by Functions排序方法
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
fruits := []string{"peach", "banana", "kiwi"}
lenCmp := func(a, b string) int {
return cmp.Compare(len(a), len(b))
}
slices.SortFunc(fruits, lenCmp)
fmt.Println(fruits)
type Person struct {
name string
age int
}
people := []Person{
Person{name: "Jax", age: 37},
Person{name: "TJ", age: 25},
Person{name: "Alex", age: 72},
}
slices.SortFunc(people,
func(a, b Person) int {
return cmp.Compare(a.age, b.age)
})
fmt.Println(people)
}
sort.Interface
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type ByAge []Person
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() {
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
sort.Sort(ByAge(people))
fmt.Println(people)
}