golang 排序任意数据结构
使用 sort.Sort() 或者 sort.Stable() 函数可完成对任意类型元素的排序。
一个内置的排序算法需要知道三个东西:序列的长度,表示两个元素比较的结果,一种交换两个元素的方式;这就是 sort.Interface 的三个方法:
type Interface interface {
    Len() int
    Less(i, j int) bool // i, j 是元素的索引
    Swap(i, j int)
}
这种方法相较于前面介绍的两种排序,用起来稍微麻烦了点,因为需要用户自定义的东西更多了,不过带来的好处也是显而易见的,更加普适。
还是以学生排序为例,在自定义的结构体上实现 srot.Interface 接口。
type Student struct {
	Name   string
	Age    int
	Height int
}
// ByAgeHeight 实现 sort.Interface 接口
type ByAgeHeight []Student
func (a ByAgeHeight) Len() int { return len(a) }
// Less 先用年龄排序,年龄相等再用身高排
func (a ByAgeHeight) Less(i, j int) bool {
	if a[i].Age < a[j].Age {
		return true
	}
	if a[i].Age > a[j].Age {
		return false
	}
	return a[i].Height < a[j].Height
}
func (a ByAgeHeight) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func main() {
	slStdnt := []Student{
		{"Alice", 23, 175},
		{"David", 18, 185},
		{"Eve", 18, 165},
		{"Bob", 25, 170},
	}
	sort.Stable(ByAgeHeight(slStdnt))
	fmt.Println(slStdnt)
}
运行输出:
[{Eve 18 165} {David 18 185} {Alice 23 175} {Bob 25 170}]
        
 
        
