For
Go's single loop statement supports counter loops, condition loops, infinite loops, and range iteration.
Go has one loop keyword: for. A loop repeats code. You can repeat a set number of times, repeat while a condition is true, repeat until code stops it, or visit each item with range.
Use the three-part form for a counter loop. A loop with only a condition keeps repeating while that condition is true. If the condition is omitted, the loop continues until its code uses break or the function returns.
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Print(i, " ")
}
n := 0
for n < 3 {
n++
}
for {
if n == 5 {
break
}
n++
}
values := []string{"Go", "by", "example"}
for i, value := range values {
fmt.Println(i, value)
}
}In production
Ranging over a slice copies each element into the loop variable. Assign through the index when you need to change the slice itself. In go.mod, the go version also affects loop variables. Go 1.22 and later create a new one for each iteration.