Go Gopher How to Go

for is Go's only looping construct. It's versatile and can replace while loops, do-while loops, and traditional for loops from other languages.

💡 Key Points

  • for is the only looping construct in Go
  • All three components (init, condition, post) are optional
  • Use break to exit a loop early
  • Use continue to skip to the next iteration
  • Variables declared in the init statement are scoped to the loop

Classic For Loop

The most basic form with initialization, condition, and post statement:

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
}
Output:
0
1
2
3
4

For as While Loop

Omit the init and post statements to create a while-style loop:

package main

import "fmt"

func main() {
    i := 0
    for i < 5 {
        fmt.Println(i)
        i++
    }
}
Output:
0
1
2
3
4

Infinite Loop with Break

Use break to exit an infinite loop:

package main

import "fmt"

func main() {
    i := 0
    for {
        if i >= 5 {
            break
        }
        fmt.Println(i)
        i++
    }
}
Output:
0
1
2
3
4

For Loop Patterns

PatternExampleDescription
for init; cond; post { }for i := 0; i < 10; i++ { }Classic three-component loop
for condition { }for i < 10 { }While-style loop
for { }for { }Infinite loop (use with break)
for range collection { }for i, v := range slice { }Iterate over arrays, slices, maps

Control Statements

StatementPurposeExample
breakExit the loop immediatelyif i > 5 { break }
continueSkip to next iterationif i%2 == 0 { continue }