golang如何对自定义类型的slice进行排序?

5 篇文章 0 订阅

golang如何对自定义类型的slice进行排序

引子

在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点赞!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值