按键排序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-

package main

import (
    "fmt"
    "sort"
)

func main() {
    // To create a map as input
    m := make(map[int]string)
    m[1] = "a"
    m[2] = "c"
    m[0] = "b"

    // To store the keys in slice in sorted order
    var keys []int
    for k := range m {
        keys = append(keys,k)
    }
    sort.Ints(keys)

    // To perform the opertion you want
    for _,k := range keys {
        fmt.Println("Key:",k,"Value:",m[k])
    }
}

输出

Key: 0 Value: b
Key: 1 Value: a
Key: 2 Value: c
原文链接:https://www.f2er.com/go/187457.html

猜你在找的Go相关文章