dictionary - 在范围循环内从 map 中删除选定的键是否安全?

标签 dictionary for-loop go

如何从 map 中删除选定的键? 将 delete() 与 range 结合是否安全,如下面的代码所示?

package main

import "fmt"

type Info struct {
    value string
}

func main() {
    table := make(map[string]*Info)

    for i := 0; i < 10; i++ {
        str := fmt.Sprintf("%v", i)
        table[str] = &Info{str}
    }

    for key, value := range table {
        fmt.Printf("deleting %v=>%v\n", key, value.value)
        delete(table, key)
    }
}

https://play.golang.org/p/u1vufvEjSw

最佳答案

这是安全的!您还可以在 Effective Go 中找到类似的示例:

for key := range m {
    if key.expired() {
        delete(m, key)
    }
}

还有 the language specification :

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If map entries that have not yet been reached are removed during iteration, the corresponding iteration values will not be produced. If map entries are 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.

关于dictionary - 在范围循环内从 map 中删除选定的键是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23229975/

相关文章:

c# - 具有重复键的 KeyValuePair

Python:Pandas 在将字典传递给 resample() 后显示 NaN

python - 在一行上组合并打印不同的变量

c - 在没有 int i = 0 的情况下循环做某事 n 次?

arrays - 在 Go 中将一个数组 append 到另​​一个数组的最快方法是什么?

dictionary - 关于方案中的 map

python - 带有类中函数字典的 self 参数

javascript - javascript中根据id删除对象

go - 我如何开始使用 Go?

ubuntu - 如何在 Ubuntu 16.04 LTS 的 golang 中正确使用多个工作空间?