Back to Concepts Roadmap
🟠 Level 2 — Flow Control
Flow Control

Loops (for & range)

The single loop keyword in Go: classic three-part loops, while-style conditions, infinite loops, and range iteration.

Real-World Analogy (Mental Model)

An automated conveyer belt: it carries items one by one (`for range`) until the batch is done, or runs continuously (`for {}`) until an emergency stop button (`break`) is pressed.

Architecture & Memory MapVisual Model
1. Classic:   for i := 0; i < 5; i++ { ... }
2. While:     for condition { ... }
3. Infinite:  for { if stop { break } }
4. Range:     for idx, val := range slice { ... }

Key Concepts & Rules To Remember

  • `for` is the ONLY looping keyword in Go (no `while` or `do-while`).
  • Four flavors: classic counting `for i := 0; i < N; i++`, condition-only `for ok`, infinite `for {}`, and collection iteration `for index, value := range collection`.
  • In Go 1.22+, loop iteration variables are created fresh per iteration, preventing closure capture bugs.
Step-by-Step Code

1. The Four Flavors of for

Because Go has no `while` keyword, `for` handles every loop use case with clean syntax:

example.goGo 1.24+
// 1. Classic Counter
for i := 0; i < 3; i++ {
    fmt.Println("Count:", i)
}

// 2. While-style
n := 1
for n < 100 {
    n *= 2
}

// 3. Range over Slice
fruits := []string{"Apple", "Banana", "Cherry"}
for idx, fruit := range fruits {
    fmt.Printf("%d: %s\n", idx, fruit)
}

Common Beginner Pitfalls & Mistakes

Mistake: Using `_` when you only want the index in `for i := range items`.
✅ Correct Way: If you only provide one variable in `for i := range items`, Go gives you the INDEX. If you want only the value, write `for _, val := range items`.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanations—expand to see why.

How many different looping keywords exist in the Go language?

Finished this lesson?

Mark it as complete to track your overall Go mastery.