Search⌘ K
AI Features

Loops

Explore the intricacies of loops in Go, including how for-range iterators return index and value, and why iterator variables are reused in each iteration. Understand common pitfalls such as variable capture within goroutines and how to fix them by declaring new variables or passing parameters correctly. This lesson helps you write efficient, bug-free loops in Go and manage concurrency safely.

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:

Go (1.16.5)
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 ...