The Power of For
Go takes a unique approach to loops: there’s only one looping keyword -for. This single construct handles all looping scenarios, from traditional counted loops to while-style iterations.
One Loop to Rule Them All: Go uses the
for keyword for all loop types. There is no while or do-while - for does it all.Loop Types in Go
Go’sfor loop can be used in three main ways:
1. While-Style Loop
Afor loop with only a condition acts like a while loop:
2. Traditional For Loop
The classic three-component loop with initialization, condition, and post statement:3. Range Loop
Iterate over a sequence using therange keyword:
Complete Example
Here’s a complete program demonstrating all three loop types:Understanding Each Loop Type
While-style loops
Use when you need to loop based on a condition, without knowing the iteration count upfrontThis is equivalent to
while (i < 5) in other languages.Traditional for loops
Use when you know exactly how many iterations you needThe structure is:
for initialization; condition; post { }Why No While Loop?
Thefor loop in Go is versatile enough to handle:
- While loops:
for i < 5 { ... } - Infinite loops:
for { ... } - Traditional for:
for i := 0; i < 5; i++ { ... } - Foreach-style:
for i := range x { ... }
Loop Control
Breaking Out of Loops
Usebreak to exit a loop early:
Skipping Iterations
Usecontinue to skip to the next iteration:
Infinite Loops
Create an infinite loop with justfor:
Common Patterns
Counting Up
Counting Down
Iterating with Step
Next Steps
With control flow mastered, you’re ready to work with collections like arrays and slices, where you’ll use these loops extensively with therange keyword.