Loops for
Context
Section titled “Context”Go has only one looping construct: for. It can be used in three main forms:
- Classic:
for initialization; condition; post {} - While‑like:
for condition {} - Infinite:
for {}(break withbreakorreturn)
Example
Section titled “Example”Print numbers from 0 to 4, then a while‑like loop, then an infinite loop with break.
Code example
Section titled “Code example”package main
import "fmt"
func main() { // Classic loop for i := 0; i < 5; i++ { fmt.Print(i, " ") } fmt.Println()
// While-like j := 0 for j < 3 { fmt.Print(j, " ") j++ } fmt.Println()
// Infinite loop k := 0 for { if k >= 2 { break } fmt.Print(k, " ") k++ } fmt.Println()}Output
Section titled “Output”0 1 2 3 40 1 20 1