写代码的时候发现需要对map[int64]int64排序,golang中sort包来解决这个问题,下面是从网上找的2个例子,备忘下。
例子一:
package main
import (
"fmt"
"sort"
)
func main()
m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
mk := make([]string, len(m))
i := 0
for k, _ := range m {
mk[i] = k
i++
}
sort.SortStrings(mk)
fmt.Println(mk)
}
例子二:
// A data structure to hold a key/value pair.
type Pair struct {
Key string
Value int
}
// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []Pair
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
// A function to turn a map into a PairList, then sort and return it.
func sortMapByValue(m map[string]int) PairList {
p := make(PairList, len(m))
i := 0
for k, v := range m {
p[i] = Pair{k, v}
}
sort.Sort(p)
return p
}