溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

golang使用sort接口實現(xiàn)排序示例

發(fā)布時間:2020-08-20 18:30:34 來源:腳本之家 閱讀:114 作者:dotcoo 欄目:編程語言

本文實例講述了golang使用sort接口實現(xiàn)排序的方法。分享給大家供大家參考,具體如下:

今天看見群里再討論排序的sort.Interface的實現(xiàn),有童鞋一直搞不定,我就上手了一下,哦耶搞定了,代碼放在這里.

其實很簡單sort.Interface借口有三個方法,給自己的struct實現(xiàn)這三個方法,然后用將自己的結(jié)構(gòu)體傳給sort.Sort方法就排序完成.

當然sort包也有幾個常用的方法sort.Float64Slice sort.IntSlise sort.StringSlise,呵呵

復(fù)制代碼 代碼如下:
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語言程序設(shè)計有所幫助。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI