在go中,map是一个无序的集合。下面的代码中,展示如何向map中添加key与value,并且最后排序key
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func stuStore() {
rand.Seed(time.Now().UnixNano())//init unix otc
stuMaps := make(map[int]map[string]interface{}) //初始化map
//循环创建10个key
for i := 0;i<10;i++ {
//获取每个key与对应的value
value,key := stuMaps[i]
//判断每个key是否存在
if !key {
//不存在则将key的value值进行map初始,用于存放个人信息
value = make(map[string]interface{})
}
//添加信息至map
value["ID"] = i
value["姓名"] = fmt.Sprintf("stu%d",i)
value["年龄"] = rand.Intn(25)
value["分数"] = rand.Float32() *100.0
//value信息添加结束,赋值给key
stuMaps[i] = value
}
//临时切片,用于存放map的key
sls := make([]int,0,128)
//循环map,将key追加至切片
for k,_ := range stuMaps {
sls= append(sls,k)
}
//对切片进行排序
sort.Ints(sls)
//对排序好的key进行输出
for _,k := range sls {
fmt.Printf("key :%d, value:%#v\n",k,stuMaps[k])
}
}
func main() {
stuStore()
}
key :0, value:map[string]interface {}{“ID”:0, “分数”:3.8371809, “姓名”:”stu0”, “年龄”:23}
key :1, value:map[string]interface {}{“ID”:1, “分数”:64.151695, “姓名”:”stu1”, “年龄”:17}
key :2, value:map[string]interface {}{“ID”:2, “分数”:30.308903, “姓名”:”stu2”, “年龄”:7}
key :3, value:map[string]interface {}{“ID”:3, “分数”:26.408901, “姓名”:”stu3”, “年龄”:4}
key :4, value:map[string]interface {}{“ID”:4, “分数”:19.945482, “姓名”:”stu4”, “年龄”:11}
key :5, value:map[string]interface {}{“ID”:5, “分数”:83.96999, “姓名”:”stu5”, “年龄”:15}
key :6, value:map[string]interface {}{“ID”:6, “分数”:22.143503, “姓名”:”stu6”, “年龄”:6}
key :7, value:map[string]interface {}{“ID”:7, “分数”:32.077267, “姓名”:”stu7”, “年龄”:0}
key :8, value:map[string]interface {}{“ID”:8, “分数”:51.639027, “姓名”:”stu8”, “年龄”:10}
key :9, value:map[string]interface {}{“ID”:9, “分数”:93.744835, “姓名”:”stu9”, “年龄”:15}