英文:
What determines the order in which the results are generated from "for range" iteration of golang map?
问题
我试图弄清楚确定 Golang map 的 "for range" 迭代结果的顺序是由什么决定的。
我发现它既不是由键的顺序确定的,也不是由插入的顺序确定的,这真的很奇怪。
我想找出这个问题。在 Golang 的源代码中,我可以在哪里找到 "for range" map 的实现?
func main() {
m := make(map[int]int)
m[1] = 2
m[2] = 3
m[0] = 1
m[4] = 5
m[3] = 4
for k, v := range m {
fmt.Println(k, v)
}
}
// 输出结果
// 1 2
// 2 3
// 0 1
// 4 5
// 3 4
英文:
I try to firgure out that what determines the order of results generated from "for range" iteration of golang map.
I found that it is neither determined by the order of keys nor by the order of pushing. which is really weired.
I want to figure this out. In terms of source code of golang, where can i find the implementation of "for range" map?
func main() {
m := make(map[int]int)
m[1] = 2
m[2] = 3
m[0] = 1
m[4] = 5
m[3] = 4
for k, v := range m {
fmt.Println(k, v)
}
}
// output
// 1 2
// 2 3
// 0 1
// 4 5
// 3 4
答案1
得分: 2
“for range”迭代golang map生成结果的顺序是由什么决定的?
没有任何决定因素,它是故意的随机/非确定性的。
你不能依赖于迭代顺序。
map的源代码可以在https://go.googlesource.com/go/+/refs/heads/master/src/runtime/map.go找到。
但是再次强调:迭代是随机的,没有什么可看的。
英文:
> I try to firgure out that what determines the order of results generated from "for range" iteration of golang map?
Nothing, it's deliberately random/non-deterministic.
You must not rely on iteration order.
Source for map is https://go.googlesource.com/go/+/refs/heads/master/src/runtime/map.go
But again: iteration is random, really. Nothing to see here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论