猿问

使用范围时,GO 是否总是以相同的顺序迭代映射条目?

这段代码会始终显示相同的结果吗?潜在问题:range总是会以相同的顺序迭代地图吗?


m := map[string]int {

    "a": 1,

    "b": 2,

    "c": 3,

    "d": 4,

    "e": 5,

    "f": 6,

}

for k, v := range m {

    fmt.Printf("%v = %v", k, v)

}


海绵宝宝撒
浏览 88回答 2
2回答

小怪兽爱吃肉

不,它是有意随机化的(以防止程序员依赖它,因为它未在语言规范中指定)。来自Go迭代顺序使用范围循环遍历地图时,未指定迭代顺序,并且不保证从一次迭代到下一次迭代是相同的。自 Go 1.0 发布以来,运行时具有随机化的 map 迭代顺序。程序员已经开始依赖 Go 早期版本的稳定迭代顺序,这在实现之间有所不同,从而导致可移植性错误。

青春有我

答案是:不,不是。我写了以下测试来断言。func Test_GO_Map_Range(t *testing.T) {&nbsp; &nbsp; originalMap := map[string]int {&nbsp; &nbsp; &nbsp; &nbsp; "a": 1,&nbsp; &nbsp; &nbsp; &nbsp; "b": 2,&nbsp; &nbsp; &nbsp; &nbsp; "c": 3,&nbsp; &nbsp; &nbsp; &nbsp; "d": 4,&nbsp; &nbsp; &nbsp; &nbsp; "e": 5,&nbsp; &nbsp; &nbsp; &nbsp; "f": 6,&nbsp; &nbsp; }&nbsp; &nbsp; getKeys := func(m map[string]int) []string{&nbsp; &nbsp; &nbsp; &nbsp; mapKeys := make([]string, len(m))&nbsp; &nbsp; &nbsp; &nbsp; i := 0&nbsp; &nbsp; &nbsp; &nbsp; for n := range m {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mapKeys[i] = n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return mapKeys&nbsp; &nbsp; }&nbsp; &nbsp; keys := getKeys(originalMap)&nbsp; &nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; assert.Equal(t, keys, getKeys(originalMap))&nbsp; &nbsp; }}我得到如下结果:Error:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Not equal:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expected: []string{"d", "e", "f", "a", "b", "c"}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; actual&nbsp; : []string{"a", "b", "c", "d", "e", "f"}Error:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Not equal:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expected: []string{"d", "e", "f", "a", "b", "c"}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; actual&nbsp; : []string{"f", "a", "b", "c", "d", "e"}Error:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Not equal:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expected: []string{"d", "e", "f", "a", "b", "c"}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; actual&nbsp; : []string{"c", "d", "e", "f", "a", "b"}Error:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Not equal:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expected: []string{"d", "e", "f", "a", "b", "c"}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; actual&nbsp; : []string{"b", "c", "d", "e", "f", "a"}Error:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Not equal:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expected: []string{"d", "e", "f", "a", "b", "c"}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; actual&nbsp; : []string{"a", "b", "c", "d", "e", "f"}
随时随地看视频慕课网APP

相关分类

Go
我要回答