英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论