本文介绍了golang使用sort接口实现排序的方法。分享给大家,供大家参考,详情如下:

今天看到群里讨论sort.Interface的实现。有些人想不通,所以我开始研究它。哦,是的,我明白了。代码在这里。

其实很简单。 sort.Interface 接口具有三个方法。为自己的结构体实现这三个方法,然后将自己的结构体传递给sort.Sort方法即可完成排序。

当然sort包还有几个常用的方法:sort.Float64Slice sort.IntSlise sort.StringSlise,哈哈

包装主
导入(
“fmt”
「排序」
)
输入 MapSorter []Item
类型项目结构 {
钥匙串
瓦尔 int64
}
func NewMapSorter(m map[string]int64) MapSorter {
ms := make(MapSorter, 0, len(m))
对于 k,v := 范围 m {
ms = 追加(ms, Item{k, v})
}
返回毫秒
}
func (ms MapSorter) Len() int {
返回长度(ms)
}
func (ms MapSorter) Less(i, j int) bool {
返回 ms[i].Val < ms[j].Val // 按值排序
//返回 ms[i].Key < ms[j].Key // 按键排序
}
func (ms MapSorter) Swap(i, j int) {
ms[i], ms[j] = ms[j], ms[i]
}
func main(){
m := map[string]int64 {
“e”:10,
“一”:2,
“d”:15,
“c”:8,
“f”:1,
“b”:12,
}
ms := NewMapSorter(m)
排序.排序(ms)
对于 _,项目 := 范围 ms {
fmt.Printf("%s:%dn", item.Key, item.Val)
}
}

希望这篇文章对大家Go语言编程有所帮助。