go - 在迭代字典时删除字典键是否安全?

标签 go

我编写了一些执行此操作的代码,并且工作正常,但是在查看代码时,我意识到我所做的可能不适用于其他语言。

举一个人为的例子:

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/

相关文章:

go - 我可以列出所有标准的 Go 包吗?

json - 在 Golang 中 Umarshalling 这个 JSON

go - Geth如何保持区 block 链状态?

go - 函数类型变量声明 - 官方 golang 文档页面上的错字

c++ - GoLang 将 C.wchar_t 转为字符串

macos - 更新到 macOS beta 4 后,go test -cover 抛出 "fatal error: unexpected signal during runtime execution"

go - golang 中的空函数

Golang 定期检查端口上打开的 TCP 连接

testing - 着色 golang 测试运行输出

go - 获取内部结构值