go 结构体切片自定义排序
常见类型的默认排序实现
go sort包默认支持int(sort.Ints(x []int))、float64s(sort.Float64s(x []float64))、string(sort.Strings(x []string))从小到大排序,反序使用类似于sort.Sort(sort.Reverse(sort.Ints(x []int)))的方式。
结构体切片的自定义排序实现
package main
import (
"fmt"
"sort"
)
type Student struct {
Age int
Score int
}
type StudentSort []Student
func (s StudentSort) Len() int {
return len(s)
}
func (s StudentSort) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s StudentSort) Less(i, j int) bool {
return s[i].Score > s[j].Score
}
func main() {
s := []Student{
{Age:15, Score:1},
{Age:16, Score:0},
{Age:17, Score:30},
{Age:18, Score:50},
{Age:19, Score:40},
}
sort.Sort(StudentSort(s))
fmt.Printf("%+v", s)
}