字典(map)
# 字典(map)
Map 使用可比较类型作为键。读取不存在的键会得到值类型的零值,逗号 ok 形式可区分“不存在”和“值恰好为零”。
counts := map[string]int{}
counts["ok"]++
value, exists := counts["timeout"]
delete(counts, "ok")
fmt.Println(value, exists)
1
2
3
4
5
2
3
4
5
Map 遍历顺序不确定,稳定输出前应提取并排序键。nil Map 可以读取但不能写入。普通 Map 不允许多个 goroutine 无同步地并发读写,共享状态应使用锁、单一所有者或适合场景的 sync.Map。