Sort Go map values by keys

后端 未结 6 607
悲哀的现实
悲哀的现实 2020-11-28 02:58

When iterating through the returned map in the code, returned by the topic function, the keys are not appearing in order.

How can I get the keys to be in order / sor

6条回答
  •  一向
    一向 (楼主)
    2020-11-28 03:16

    According to the Go spec, the order of iteration over a map is undefined, and may vary between runs of the program. In practice, not only is it undefined, it's actually intentionally randomized. This is because it used to be predictable, and the Go language developers didn't want people relying on unspecified behavior, so they intentionally randomized it so that relying on this behavior was impossible.

    What you'll have to do, then, is pull the keys into a slice, sort them, and then range over the slice like this:

    var m map[keyType]valueType
    keys := sliceOfKeys(m) // you'll have to implement this
    for _, k := range keys {
        v := m[k]
        // k is the key and v is the value; do your computation here
    }
    

提交回复
热议问题