For Loops
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
foris the only looping construct in Go- All three components (init, condition, post) are optional
- Use
breakto exit a loop early - Use
continueto 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)
}
}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++
}
}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++
}
}0
1
2
3
4
For Loop Patterns
| Pattern | Example | Description |
|---|---|---|
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
| Statement | Purpose | Example |
|---|---|---|
break | Exit the loop immediately | if i > 5 { break } |
continue | Skip to next iteration | if i%2 == 0 { continue } |