for, range, and the loop variable
Go has one loop. Since 1.22 each iteration has its own variable — older articles are wrong about this.
There is no separate while and no do. There is for in three calm forms:
for i := 0; i < n; i++ { }
for len(items) > 0 { }
for { } // пока сами не выйдете
The way out is break. The next iteration is continue. for i, v := range items walks a slice, an array, a map, a string, or a channel. Since Go 1.22 you can write for i := range 10: these are the numbers from 0 through 9 inclusive. The upper bound is not included.
The walk order over a map is random. Do not build a test on it that claims "the string is always abc". If you need an order, collect the keys and sort them.
The loop variable
Before Go 1.22 the loop variable was one for the whole loop. A closure that captured it saw the last value. That is the famous bug, and the remedy is v := v inside the body.
Starting with Go 1.22 each iteration has its own variable. This code prints 012, not 333:
var fns []func()
for i := 0; i < 3; i++ {
fns = append(fns, func() { fmt.Print(i) })
}
for _, f := range fns {
f()
}
This is the contract of modern Go, not "usually so". Old code with v := v is still correct. It is simply no longer required. If you maintain a module with go 1.21 in go.mod, the old semantics are still alive: the version in the module decides, not the compiler version on a colleague's laptop.
range over a slice takes the value, a copy of the element. Changing v does not change the slice. To replace an element, write into items[i]. For large structs people sometimes take a pointer to the element, but then you must not hold that pointer after the slice has moved in memory. An index is simpler and more honest.
Practice
A closure and a loop
What will the program print on Go 1.22 or newer? Write the digits with no separator.
var fns []func() for i := 0; i < 3; i++ { fns = append(fns, func() { fmt.Print(i) }) } for _, f := range fns { f() }range over a number
Which values does
itake in the loopfor i := range 3on Go 1.22 or newer?- 1, 2, 3
- 0, 1, 2
- 0, 1, 2, 3
- Only 3
A copy of the element
There is
items := []int{1, 2, 3}and the loopfor _, v := range items { v = 0 }. What ends up initems?- [0 0 0]
- [1 2 3]
- nil
- The code does not compile