For
Go's single loop statement supports counter loops, condition loops, infinite loops, and range iteration.
Go has one loop keyword: for. It supports a counter, a condition, no condition, or iteration with range.
Use the three-part form for a counter loop. A condition-only loop works like while in other languages. An omitted condition repeats until the body breaks or 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 mutate the slice. Since Go 1.22, loop variables are per iteration when the module's go directive is 1.22 or later.
Enjoyed this? Get more software craft delivered to your inbox.