本文實(shí)例講述了golang使用sort接口實(shí)現(xiàn)排序的方法。分享給大家供大家參考,具體如下:
今天看見群里再討論排序的sort.Interface的實(shí)現(xiàn),有童鞋一直搞不定,我就上手了一下,哦耶搞定了,代碼放在這里.
其實(shí)很簡單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)
}
}
希望本文所述對大家Go語言程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Go 語言中的空接口(推薦)
- Go語言使用swagger生成接口文檔的方法
- 淺談django不使用restframework自定義接口與使用的區(qū)別
- 使用Django開發(fā)簡單接口實(shí)現(xiàn)文章增刪改查
- Golang 使用接口實(shí)現(xiàn)泛型的方法示例
- Django使用AJAX調(diào)用自己寫的API接口的方法
- golang基礎(chǔ)之Interface接口的使用
- golang中的空接口使用詳解