设置地图迭代顺序的种子。

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

Go set seed for map iteration order

问题

在Go语言中,映射(map)的迭代顺序是不确定的,可能会在每次运行时都有所变化。是否有办法为此设置一个种子,以便同一个Go程序的两次运行具有一致的迭代顺序?

英文:

In go, map iteration order is not specified, and may vary from run to run. Is there any way to set a seed for this, such that two runs of the same go program will have consistent iteration order?

答案1

得分: 2

简介:
使用官方的range + map是不可能的,但你可以使用第三方库,如评论中所提到的。

原因:
从这里可以看到go/src/runtime/map.go#mapiterinit,地图的遍历使用go/src/runtime/stubs.go#fastrand来随机选择起始位置,但fastrand()的结果每次都会改变,你无法每次决定顺序。

建议简要阅读发布的源代码的重要部分,一切都非常简单明了。

英文:

Brief:
Use official range + map is impossible, but you can use 3rd party libraries, as mentioned in the comments.

Why:
As you can see from here go/src/runtime/map.go#mapiterinit, the traversal of the map uses go/src/runtime/stubs.go#fastrand to randomly choose the starting position, but the result of fastrand() is changed every time, you can't decide the order each time.

It is recommended to briefly read the important parts of the posted source code, everything is very simple and clear.

huangapple
  • 本文由 发表于 2022年9月7日 07:16:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/73628597.html
匿名

发表评论

匿名网友

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

确定