Chapter 40: Go For Loops

Go for loop

In Go there is only one loop keyword: for There is no while, no do-while, no foreach, no repeat-until. Everything that needs repetition is done with for — and Go gives it four very clean and idiomatic forms.

Let me explain all of them like we’re sitting together with VS Code open — slowly, with many runnable examples, common patterns, style tips, and real-world use cases.

1. The Four Idiomatic Forms of for in Go

# Name / Style Syntax example When you use it Most common?
1 Classic C-style for for i := 0; i < 10; i++ { … } Counting loops, known number of iterations ★★★★☆
2 While-style (condition only) for condition { … } “while” loops — continue while condition true ★★★★☆
3 Infinite loop for { … } Event loops, servers, “while true” ★★★☆☆
4 Range loop (for-range) for i, v := range collection { … } Iterating over slices, arrays, maps, strings, channels ★★★★★ (the most used)

2. Form 1 – Classic C-style for (counting loop)

This is the one most people know from other languages.

Go

3. Form 2 – While-style for (only condition)

This is how you write a classic “while” loop in Go.

Go

Very common real-world pattern:

Go

4. Form 3 – Infinite for loop

Just for { … } — continues forever until you break, return, or os.Exit.

Go

Real-world usage — servers, event loops, workers:

Go

5. Form 4 – The Most Important One: for range (iteration over collections)

This is the most frequently used loop style in real Go code.

Go

6. Style & Best Practices (2025–2026)

  • Prefer for range whenever you iterate over a collection → for i := range slice { … } if you only need index → for _, v := range slice { … } if you only need value
  • Avoid deep nesting inside loops — prefer early continue / break
  • Use break and continue with labels when needed (rare but powerful)
Go

7. Quick Practice – Try These

  1. Print even numbers from 0 to 20 using classic for
  2. Print all elements of a slice using for range
  3. Sum all values in a map using for range
  4. Create an infinite loop that counts to 10 then breaks

Which form do you think you’ll use most often in real projects?

Any part still confusing?

  • Difference between for range on string vs slice?
  • How range works with maps (random order)?
  • When to use classic for vs range?
  • Or ready to move to functions next?

Keep running these loop examples — once you feel comfortable with all four forms, you’ll be able to express almost any repetition logic cleanly in Go.

You’re making excellent progress — keep asking! 💪🇮🇳🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *