我编写了一些执行此操作的代码,并且工作正常,但是在查看代码时,我意识到我所做的可能不适用于其他语言。
举一个人为的例子:
dict := map[string]string{ "a": "1", "b": "2" }
for key, val := range dict {
fmt.Println(val)
delete(dict, "b")
}
这会打印“1”和“2”,当我检查 dict
时之后是{ "a": "1" }
仅。
所以,我的印象是这样做是安全的,但我想知道为什么?
是range dict
在内部创建副本?
最佳答案
一如既往,the spec是最终的答案。下"For statements with range clause", item 3 (强调我的):
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.
关于go - 在迭代字典时删除字典键是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56048259/