dictionary - 在 Golang 中添加映射键的安全方法

标签 dictionary go

由于这个事实:

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.

在迭代期间将键值添加到映射是不安全的:

var m = make(map[string]int)
m["1"] = 1
m["2"] = 2
m["3"] = 3

for k, v := range m {
    if strings.EqualFold( "2", k){
        m["4"] = 4
    }
    fmt.Println(k, v)
}

有时会生成 "4" key ,有时不会。

让它始终生成的解决方法是什么?

最佳答案

使用要添加到原始 map 的项目创建另一个 map ,并在迭代后合并它们。

var m = make(map[string]int)
m["1"] = 1 
m["2"] = 2 
m["3"] = 3 

var n = make(map[string]int)

for k := range m { 
    if strings.EqualFold("2", k) {
        n["4"] = 4 
    }   
}   

for k, v := range n { 
    m[k] = v 
}   

for _, v := range m { 
    fmt.Println(v)
}

关于dictionary - 在 Golang 中添加映射键的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51023359/

相关文章:

c++ - 请求 ‘insert’中的成员 ‘x’,非类类型

java - 我应该使用哪种 map ?

ssl - 如何在 Go 中缓存/重用 TLS 连接

parsing - 如何在 Golang 中解析 IST 格式的日期?

go - 如何强制go子流程加载插件?

python - Sphinx 记录字典内容(模块常量)

Python字典理解示例

java - 我可以获取 map 的一部分并测试我使用的 key 吗?

go - 如何为包含 DB conn 之类的应用程序包设置全局配置?

database - 我可以使用 golang 为 sqlite3 数据库中的每个新用户增加数值吗?