What are the pitfalls when iterating over a map in Go?
sobes.tech AI
Answer from AI
When iterating over a map in Go, there are several important features and pitfalls:
-
The iteration order is not defined and can change — each time you iterate over a map, the order of keys may be different. You cannot rely on a fixed order.
-
Modifying the map during iteration — if you add or remove elements during iteration, the behavior is undefined and may lead to a panic or skipping elements.
-
Copying keys and values — during iteration, the variables for key and value are overwritten, so if you save their addresses, you may get unexpected results.
Example of incorrect key address saving:
m := map[string]int{"a":1, "b":2}
var keys []*string
for k := range m {
keys = append(keys, &k) // all elements will point to the same variable k
}
Correct way is to create a copy inside the loop:
for k := range m {
keyCopy := k
keys = append(keys, &keyCopy)
}
In summary, when working with maps, it is important to remember the undefined order, not to modify the map during iteration, and to handle loop variables carefully.