按键排序golang映射值

前端之家收集整理的这篇文章主要介绍了按键排序golang映射值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当迭代通过主题函数返回的代码中的返回映射时,键不会按顺序显示

我如何获得按顺序排序/排序的地图,使键的顺序和值对应?

这里是the code

Go blog: Go maps in action有一个很好的解释。

When iterating over a map with a range loop,the iteration order is
not specified and is not guaranteed to be the same from one iteration
to the next. Since Go 1 the runtime randomizes map iteration order,as
programmers relied on the stable iteration order of the prevIoUs
implementation. If you require a stable iteration order you must
maintain a separate data structure that specifies that order.

这里是我的修改版本的示例代码
http://play.golang.org/p/dvqcGPYy3-

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "sort"
  6. )
  7.  
  8. func main() {
  9. // To create a map as input
  10. m := make(map[int]string)
  11. m[1] = "a"
  12. m[2] = "c"
  13. m[0] = "b"
  14.  
  15. // To store the keys in slice in sorted order
  16. var keys []int
  17. for k := range m {
  18. keys = append(keys,k)
  19. }
  20. sort.Ints(keys)
  21.  
  22. // To perform the opertion you want
  23. for _,k := range keys {
  24. fmt.Println("Key:",k,"Value:",m[k])
  25. }
  26. }

输出

  1. Key: 0 Value: b
  2. Key: 1 Value: a
  3. Key: 2 Value: c

猜你在找的Go相关文章