“for range”迭代golang map时,结果生成的顺序是由什么决定的?

huangapple go评论89阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年9月5日 20:32:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73609431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定