在go中,map是一个无序的集合。下面的代码中,展示如何向map中添加key与value,并且最后排序key

    1. package main
    2. import (
    3. "fmt"
    4. "math/rand"
    5. "sort"
    6. "time"
    7. )
    8. func stuStore() {
    9. rand.Seed(time.Now().UnixNano())//init unix otc
    10. stuMaps := make(map[int]map[string]interface{}) //初始化map
    11. //循环创建10个key
    12. for i := 0;i<10;i++ {
    13. //获取每个key与对应的value
    14. value,key := stuMaps[i]
    15. //判断每个key是否存在
    16. if !key {
    17. //不存在则将key的value值进行map初始,用于存放个人信息
    18. value = make(map[string]interface{})
    19. }
    20. //添加信息至map
    21. value["ID"] = i
    22. value["姓名"] = fmt.Sprintf("stu%d",i)
    23. value["年龄"] = rand.Intn(25)
    24. value["分数"] = rand.Float32() *100.0
    25. //value信息添加结束,赋值给key
    26. stuMaps[i] = value
    27. }
    28. //临时切片,用于存放map的key
    29. sls := make([]int,0,128)
    30. //循环map,将key追加至切片
    31. for k,_ := range stuMaps {
    32. sls= append(sls,k)
    33. }
    34. //对切片进行排序
    35. sort.Ints(sls)
    36. //对排序好的key进行输出
    37. for _,k := range sls {
    38. fmt.Printf("key :%d, value:%#v\n",k,stuMaps[k])
    39. }
    40. }
    41. func main() {
    42. stuStore()
    43. }

    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}