简单使用sort
1 package main 2 3 import ( 4 "fmt" 5 "math/rand" 6 "sort" 7 "time" 8 ) 9 10 type KVal struct { 11 K int 12 Val interface{} //Arbitrary data 13 } 14 15 type KData []*KVal 16 17 func (v KData) Len() int { return len(v) } 18 func (v KData) Less(i, j int) bool { return v[i].K < v[j].K } 19 func (v KData) Swap(i, j int) { v[i], v[j] = v[j], v[i] } 20 21 const ( 22 NUM = 5 23 ) 24 25 func main() { 26 rand.Seed(time.Now().Unix()) 27 datas := make(KData, 0, NUM) 28 for i := 0; i < NUM; i++ { 29 datas = append(datas, genData(i)) 30 } 31 sort.Sort(datas) 32 for _, v := range datas { 33 fmt.Println(v) 34 } 35 } 36 37 func genData(k int) *KVal { 38 total := rand.Intn(10) + 1 39 kVak := &KVal{ 40 K: rand.Intn(9999), 41 Val: make([]int, 0, total), 42 } 43 val := make([]int, 0, total) 44 for total > 0 { 45 val = append(val, rand.Intn(1000)) 46 total-- 47 } 48 kVak.Val = val 49 return kVak 50 }