本文實例講述了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語言程序設計有所幫助。
您可能感興趣的文章:- Go 語言中的空接口(推薦)
- Go語言使用swagger生成接口文檔的方法
- 淺談django不使用restframework自定義接口與使用的區別
- 使用Django開發簡單接口實現文章增刪改查
- Golang 使用接口實現泛型的方法示例
- Django使用AJAX調用自己寫的API接口的方法
- golang基礎之Interface接口的使用
- golang中的空接口使用詳解