常见类型的默认实现
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)
}
标签:sort,StudentSort,自定义,int,Age,切片,Score,func,go
From: https://www.cnblogs.com/WJQ2017/p/18385530