Introduction
for is Go’s only looping construct. Unlike other languages, Go doesn’t have while or do-while loops - the for loop handles all iteration needs through various forms.
The Code
Loop Variants
While-Style Loop (Condition Only)
while loop in other languages. It continues as long as the condition is true.
Classic Three-Component Loop
for loop with:
- Initialization:
j := 0 - Condition:
j < 3 - Post statement:
j++
Range Over Integer
for i := 0; i < 3; i++ when you just need the index.
The
range over integer syntax is available in Go 1.22 and later.Infinite Loop
for loop without any condition runs forever until explicitly stopped with break or return.
Infinite loops are useful for servers, event loops, and other continuously running processes.
Using Continue
continue skips to the next iteration of the loop. This example prints only odd numbers (1, 3, 5).
Loop Control Statements
| Statement | Effect |
|---|---|
break | Exit the loop entirely |
continue | Skip to next iteration |
return | Exit the enclosing function |
Common For Loop Patterns
Iterate N Times
Iterate Until Condition
Iterate Forever
Iterate with Range
Key Takeaways
foris the only loop in Go - it replaceswhileanddo-while- Three forms: condition-only, three-component, and infinite
rangeover integers provides a clean way to iterate N times- Use
breakto exit loops andcontinueto skip iterations - No parentheses needed around conditions, but braces are required
- Loop variables declared in the initialization are scoped to the loop