Go 自定义排序

273 阅读1分钟

我们知道java自定义排序可以使用

Collections.sort(list, (a,b)->a[0]-b[0]);

那么go的自定义排序怎么做呢?

例如,当前有一个struct

type tree struct{ height, x, y int }

还有一个包含strcut的list

fore := make([]tree, n, n)

我们要对于fore进行排序,首先需要一个函数interface

type ByHeight []tree

需要实现 sort.Interface 接口的 LenLess和 Swap 方法

func (a byHeight) Len() int {
   return len(a)
}
func (s byHeight) Swap(i, j int) {
   s[i], s[j] = s[j], s[i]
}
func (s byHeight) Less(i, j int) bool {
   return s[i].height < s[j].height
}

注意,以上三个方法需要在函数外定义。 此时,我们可以定义数组或者是切片

//t := [10]tree{}
f := make([]tree, 10, 10)
sort.Sort(ByHeight(f))