Loops in Go

The for loop is the only looping construct in Go. It uses a standard C-like syntax but without the parentheses around the components.

Basic Syntax

for INITIAL; CONDITION; AFTER {
    // do something
}
  • INITIAL: Run once at the beginning. Usually used to declare a counter variable (scoped to the loop).
  • CONDITION: Evaluated before every iteration. If it’s false, the loop stops.
  • AFTER: Run at the end of every iteration. Usually used to increment the counter.

Example

for i := 0; i < 10; i++ {
    fmt.Println(i)
}
// Prints numbers from 0 to 9

Scope

Variables declared in the INITIAL statement are only accessible within the loop’s body.