如何从 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)
}
}
最佳答案
这是安全的!您还可以在 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/