Contents
Dig101 is back — digging into mechanics behind everyday Go.
Two common iteration forms: for and for-range. Range has sharp edges — the usual traps below.
Update: Go 1.22 gives each iteration its own loop variables, so the classic “shared loop var” bugs below do not apply on 1.22+ unless you use an older release.
0x01 Can you collect pointers to every element?
1 | arr := [2]int{1, 2} |
No — same surprise on []int{1, 2} or map[int]int{1:1, 2:2}.
for-range is syntactic sugar. The compiler copies the container (for arrays/slices/maps as the spec defines), and v is one variable reused each iteration. Taking &v yields one address; after the loop it holds the last value (2, 2).
Rough lowering:
1 | // len_temp := len(range) |
Fixes:
- Shadow with a per-iteration local:
1 | for _, v := range arr { |
- Index into the original:
1 | for k := range arr { |
Once you see the single loop variable, the rest is faster to spot.
0x02 Does ranging stop if you append to a slice?
1 | v := []int{1, 2, 3} |
Yes — iteration length was fixed from the copy at range entry; appends to v do not extend this loop.
0x03 Large arrays and wasted copies
1 | var arr = [102400]int{1, 1, 1} |
Wasteful — ranging copies the whole array.
Options:
for i, n := range &arrfor i, n := range arr[:]
Quiz: why don’t huge slices and maps pay the same full-value copy? (Hint: what the range clause actually duplicates.)
0x04 Zeroing a big array via range
1 | var arr = [102400]int{1, 1, 1} |
Efficient — the compiler can lower “assign zero” loops to memclr; see range.go memclrrange:
1 | // Lower n into runtime·memclr if possible, for |
0x05 Deleting map keys while ranging
1 | var m = map[int]int{1: 1, 2: 2, 3: 3} |
You won’t see deleted keys later in this range if they were not visited yet. Map iteration picks a random start bucket; deleting an unvisited key removes it from the rest of this pass.
0x06 Inserting during map range
1 | var m = map[int]int{1:1, 2:2, 3:3} |
Maybe — you may see 44 in the output for the same iteration-order reasons. Repeat to see both outcomes:
1 | var createElemDuringIterMap = func() { |
0x07 Goroutines in the loop body
1 | var m = []int{1, 2, 3} |
Broken — expect 222, not a permutation of 0,1,2. Same loop-variable capture.
Fixes:
1 | for i := range m { |
1 | for i := range m { |
Even a “simple” for-range has plenty under the hood.
Code: NewbMiao/Dig101-Go.
References:
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
