欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2016年07月22日 16:44:45   作者:dotcoo  
這篇文章主要介紹了golang使用sort接口實(shí)現(xiàn)排序的方法,簡(jiǎn)單分析了sort接口的功能并實(shí)例演示了基于sort接口的排序?qū)崿F(xiàn)方法,需要的朋友可以參考下

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

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

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

當(dāng)然sort包也有幾個(gè)常用的方法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)
    }
}

希望本文所述對(duì)大家Go語言程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論