在 Go 博客中,这是按顺序打印 map 的方法。
http://blog.golang.org/go-maps-in-action
import "sort"
var m map[int]string
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
但是如果我有像 var m map[string]string
这样的字符串键呢?
我不知道如何按顺序打印出字符串(未排序,按照在 map 容器中创建字符串的顺序)
这个例子在我的 Playground 上http://play.golang.org/p/Tt_CyATTA3
如您所见,它一直在打印困惑的字符串,所以我尝试将整数值映射到 map[string]string
但我仍然无法弄清楚如何映射 map[string 的每个元素]字符串
。
最佳答案
好吧,博客提到迭代顺序是随机的:
"...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"
这个解决方案有点简单,你有一个单独的 slice ,其中的键可以根据需要排序:
"...If you require a stable iteration order you must maintain a separate data structure that specifies that order."
因此,要按预期工作,请创建一个具有正确顺序的额外 slice ,然后迭代结果并按该顺序打印。
order := []string{"i", "we", "he", ....}
func String(result map[string]string) string {
for _, v := range order {
if present in result print it,
}
... print all the Non-Defined at the end
return stringValue
}
看到它在这里运行:http://play.golang.org/p/GsDLXjJ0-E
关于string - 映射字符串中的有序迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19127121/