Loops

Learn about loops in Go.

range iterator returns two values

A trap for early beginners is that for-range in Go works a bit differently than its equivalents in other languages. It returns one or two variables: the first of those two is an iteration index (or a map key if a map is iterated on) and second is the value. If only one variable is used, then it’s the index:

Press + to interact
package main
import "fmt"
func main() {
slice := []string{"one", "two", "three"}
for v := range slice {
fmt.Println(v) // 0, 1, 2
}
for _, v := range slice {
fmt.Println(v) // one two three
}
}

for loop iterator variables are reused

In loops, the same iterator variable is reused for every iteration. If you take its address, it will be the same address each time. This means the value of the iterator variable gets ...