Due to this fact:
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.
It's not safe to add key-values to map during iteration:
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)
}
Sometimes "4"
key is produced, sometimes not.
What is the workaround to make it always produced?
Create another map with the items you want to add to the original map, and after the iteration, you merge them.
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)
}