Loops
Go has one loop keyword, for. It covers C-style three-clause loops, while-style conditions, infinite loops, and range over strings, arrays, slices, maps, and channels.
Detailed Explanation
You need to retry a request, walk a slice of IDs, or wait on a channel. In C you pick among for, while, and do/while. In Go you write for every time and change the clause. That single keyword is a readability choice: there is one place to look for repetition, and gofmt always shapes it the same way.
The three shapes without range.
for i := 0; i < n; i++ { }is the counted loop. The init statement runs once. The condition is checked before every iteration. The post statement runs after each body.for err != nil { }is the while loop. No parens, braces required, condition must bebool.for { }is infinite. You leave withreturn,break, oros.Exit.
There is no do/while. If you must run the body once before the test, write the body, then for condition { with the same body, or invert the test with break.
break and continue. break leaves the innermost for, switch, or select. That last part is the trap: a break inside a switch inside a loop leaves the switch. Label the loop (retry:) and write break retry when you mean the loop. continue starts the next iteration, running the post statement first in a three-clause loop.
Loop variables are per-iteration since Go 1.22. Historically for i := range s { go f(&i) } shared one i across goroutines. From Go 1.22 each iteration has its own i. The go line in the module file selects this. If you maintain older code, capture the value: i := i inside the loop, or pass i as an argument to the goroutine.
There is no else on loops. Python's for/else does not exist. Track whether you broke with a flag, or structure the function so the success path returns inside the loop and the "never found" path is after it.
What it costs. A for over an index is as cheap as C. A range over a slice is equally cheap and harder to get wrong. A range over a string walks runes, not bytes, which is the right default for text and the wrong default for checksums. Prefer range unless you need the index arithmetic a three-clause loop makes obvious.
Code Examples
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println(i)
}
n := 3
for n > 0 {
n--
}
for {
break
}
}func find(ids []int, target int) int {
for i, id := range ids {
if id == target {
return i
}
}
return -1
}func leaveLoop(codes []int) int {
scan:
for i, c := range codes {
switch {
case c >= 500:
break scan
case c == 0:
continue scan
}
_ = i
}
return -1
}Common Gotchas
`break` inside `switch` or `select` does not leave the `for`
label the loop when you need to exit both.
Pre-1.22 loop variables are shared across iterations
closures and goroutines that capture `i` see the final value. Check the `go` line in `go.mod`.
There is no `do`/`while`
an empty `for` condition is an infinite loop, not a "run once."
The condition must be `bool`
`for n { }` does not compile. Write `for n > 0`.