golang如何对自定义类型的slice进行排序
- 引子
- 实现
- 代码
- 验证
- 小结
引子
在golang的sort包里,可以对
实现
其实在sort包里,golang已经把排序使用的接口都已经定义好了。
1 2 3 4 5 6 7 8 9 10 11 12 | // 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即可。
然后就可以使用
代码
1 2 3 4 5 | 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] } |
验证
1 2 3 4 5 6 7 | 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:
1 2 | before: [9 10 8 7 4 3 5 2 6 1] after : [1 2 3 4 5 6 7 8 9 10] |
小结
最近因为项目需要。开始学习