引子
在golang的sort包里,可以对int
类型、float64
类型和string
类型这三种类型的slice排序。如果我们相对其他类型比如int64或者自定义类型的slice进行排序该如何做呢?
实现
其实在sort包里,golang已经把排序使用的接口都已经定义好了。
// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
我们只需要对自定义类型或int64类型的slice实现上面的三个接口API即可。
然后就可以使用sort.Sort()
或者sort.Stable()
进行排序了。
代码
type TimestampSlice []int64
func (a TimestampSlice) Len() int { return len(a) }
func (a TimestampSlice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a TimestampSlice) Less(i, j int) bool { return a[i] < a[j] }
验证
func main() {
timestampSLice := TimestampSlice{9, 10, 8, 7, 4, 3, 5, 2, 6, 1}
fmt.Println("before:", timestampSLice)
sort.Sort(timestampSLice)
//sort.Stable(timestampSLice)
fmt.Println("after :", timestampSLice)
}
output:
before: [9 10 8 7 4 3 5 2 6 1]
after : [1 2 3 4 5 6 7 8 9 10]
小结
最近因为项目需要。开始学习go
,边学边用。真心觉得他简洁、好用,还能看到很多包里面的源代码。源码是第一手资料,比看任何文章都来的直接。为go
点赞!