ARTICLE AD BOX
I’m experimenting with Go’s for range loop and goroutines, and I ran into behavior I can’t explain.
This example prints inconsistent or duplicated values:
Output varies per run:
goroutine: 1 one goroutine: 2 two goroutine: 2 twoOr:
goroutine: 1 one goroutine: 2 two goroutine: 3 three // I never actually ranged over this keyOr even:
goroutine: 1 one goroutine: 1 oneWhy does range m seem to produce inconsistent keys when the map is modified during iteration?
Does Go internally rehash, resize, or re-randomize map buckets during iteration?
Does the loop variable get copied before or after a rehash?
Is this behaviour guaranteed, undefined, or just an artifact of how map iteration works in Go 1.22+?
Why do goroutines sometimes see duplicate keys even though range supposedly visits each element once?
