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.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package main import "fmt" func main() { // Print numbers 0 to 9 for i := 0; i < 10; i++ { fmt.Println(i) } // Sum of first 20 numbers sum := 0 for i := 1; i <= 20; i++ { sum += i } fmt.Println("Sum of 1 to 20 =", sum) // 210 // Step by 2 for i := 0; i <= 10; i += 2 { fmt.Print(i, " ") // 0 2 4 6 8 10 } } |
3. Form 2 – While-style for (only condition)
This is how you write a classic “while” loop in Go.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
count := 1 for count <= 5 { fmt.Println("Count is", count) count++ // very important — otherwise infinite loop! } fmt.Println("Done") |
Very common real-world pattern:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Read lines until EOF or error var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Println("Error reading file:", err) } |
4. Form 3 – Infinite for loop
Just for { … } — continues forever until you break, return, or os.Exit.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Simple infinite loop with break i := 0 for { i++ fmt.Println("Looping…", i) if i >= 5 { break // escape the loop } } |
Real-world usage — servers, event loops, workers:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
for { conn, err := listener.Accept() if err != nil { log.Println("Accept error:", err) continue } go handleConnection(conn) // handle in goroutine } |
5. Form 4 – The Most Important One: for range (iteration over collections)
This is the most frequently used loop style in real Go code.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// Slice / array fruits := []string{"apple", "banana", "cherry", "date"} for index, fruit := range fruits { fmt.Printf("Index %d → %s\n", index, fruit) } // Ignore index (very common) for _, fruit := range fruits { fmt.Println("Fruit:", fruit) } // String → iterates over runes (Unicode code points) for i, r := range "హైదరాబాద్" { fmt.Printf("Position %d → rune %c (code %U)\n", i, r, r) } // Map population := map[string]int{ "Hyderabad": 10000000, "Bangalore": 13000000, } for city, pop := range population { fmt.Printf("%s has %d people\n", city, pop) } // Channel (we'll see more later) ch := make(chan string) go func() { ch <- "message 1" ch <- "message 2" close(ch) }() for msg := range ch { fmt.Println("Received:", msg) } |
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)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
outer: for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if i*j == 12 { fmt.Println("Found 12 at", i, j) break outer // breaks both loops } } } |
7. Quick Practice – Try These
- Print even numbers from 0 to 20 using classic for
- Print all elements of a slice using for range
- Sum all values in a map using for range
- 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! 💪🇮🇳🚀
