温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

golang使用sort接口实现排序示例

发布时间:2020-08-20 18:30:34 来源:脚本之家 阅读:105 作者:dotcoo 栏目:编程语言

本文实例讲述了golang使用sort接口实现排序的方法。分享给大家供大家参考,具体如下:

今天看见群里再讨论排序的sort.Interface的实现,有童鞋一直搞不定,我就上手了一下,哦耶搞定了,代码放在这里.

其实很简单sort.Interface借口有三个方法,给自己的struct实现这三个方法,然后用将自己的结构体传给sort.Sort方法就排序完成.

当然sort包也有几个常用的方法sort.Float64Slice sort.IntSlise sort.StringSlise,呵呵

复制代码 代码如下:
package main
import (
    "fmt"
    "sort"
)
type MapSorter []Item
type Item struct {
    Key string
    Val int64
}
func NewMapSorter(m map[string]int64) MapSorter {
    ms := make(MapSorter, 0, len(m))
    for k, v := range m {
        ms = append(ms, Item{k, v})
    }
    return ms
}
func (ms MapSorter) Len() int {
    return len(ms)
}
func (ms MapSorter) Less(i, j int) bool {
    return ms[i].Val < ms[j].Val // 按值排序
    //return 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,
        "a": 2,
        "d": 15,
        "c": 8,
        "f": 1,
        "b": 12,
    }
    ms := NewMapSorter(m)
    sort.Sort(ms)
    for _, item := range ms {
        fmt.Printf("%s:%d\n", item.Key, item.Val)
    }
}

希望本文所述对大家Go语言程序设计有所帮助。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI