Go•Loops
Go Unified For Loop: Traditional, While-Style, and Range Iteration
In Go, for is the single, unified keyword for all looping semantics. Rather than providing separate while or do-while constructs, Go for handles traditional three-component counters (for init; cond; post), single-condition while loops (for cond), infinite daemon loops (for {}), and zero-allocation slice/map traversal via the range clause.
Syntax
for i := 0; i < 5; i++ { ... } // 3-component
for hasMore { ... } // while-style
for idx, val := range slice {} // range clause
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| for init; cond; post | Standard Loop | Traditional counter loop with initialization, condition, and step increment. |
| for condition | While-Style Loop | Executes repeatedly while condition evaluates to true (Go equivalent of while). |
| for idx, val := range | Range Clause | Iterates over arrays, slices, maps, strings, and channels yielding index and value. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import "fmt"
func main() {
// 1. Classical 3-component counter loop
fmt.Println("=== 1. Three-Component Counter Loop ===")
for step := 1; step <= 3; step++ {
fmt.Printf("Step %d: Power of two = %d\n", step, 1<<step)
}
// 2. While-style single condition loop
fmt.Println("\n=== 2. While-Style Queue Halving Loop ===")
bufferSlots := 16
cycles := 0
for bufferSlots > 2 {
cycles++
fmt.Printf("Cycle %d: Active buffer slots = %d\n", cycles, bufferSlots)
bufferSlots /= 2
}
fmt.Printf("Buffer stabilized at %d slots\n", bufferSlots)
// 3. Range clause iteration over slice with index and copy
fmt.Println("\n=== 3. Slice Traversal via Range Clause ===")
pipelineMicroservices := []string{"auth-vault", "event-router", "db-writer"}
for idx, service := range pipelineMicroservices {
fmt.Printf("Service #%d: [%s] -> Operational\n", idx+1, service)
}
// 4. Value-only range iteration using blank identifier
fmt.Println("\n=== 4. Value-Only Traversal (Discarding Index) ===")
for _, service := range pipelineMicroservices {
fmt.Printf("Dispatched heartbeat probe to: %s\n", service)
}
}Expected Output:
=== 1. Three-Component Counter Loop === Step 1: Power of two = 2 Step 2: Power of two = 4 Step 3: Power of two = 8 === 2. While-Style Queue Halving Loop === Cycle 1: Active buffer slots = 16 Cycle 2: Active buffer slots = 8 Cycle 3: Active buffer slots = 4 Buffer stabilized at 2 slots === 3. Slice Traversal via Range Clause === Service #1: [auth-vault] -> Operational Service #2: [event-router] -> Operational Service #3: [db-writer] -> Operational === 4. Value-Only Traversal (Discarding Index) === Dispatched heartbeat probe to: auth-vault Dispatched heartbeat probe to: event-router Dispatched heartbeat probe to: db-writer
How It Works: Step-by-Step
- Lines 7-10: Demonstrates 3-component loop using bitshift operator (1<<step).
- Lines 14-20: Uses single-condition while-style loop to halve bufferSlots until condition fails.
- Lines 24-27: Range clause iterates over slice yielding 0-indexed idx and element copy service.
- Lines 31-33: Uses blank identifier _ to cleanly discard the index when only the value is required.
Key Concepts
- Go intentionally omits while and do-while keywords to maintain a minimal, orthogonal language grammar.
- A for loop with no components (for { ... }) creates an infinite loop, commonly broken with break or return.
- The range clause returns copies of values. Mutating the val variable inside range does not modify the underlying slice.
- If you only need the index in a range loop, you can omit the second variable entirely: for idx := range slice.
Common Mistake: Taking the memory address of the range iteration variable
In older Go versions (pre-1.22), the range variable was reused in each iteration. Taking &val inside a loop closure captured the same address across iterations.
❌ Incorrect
for _, item := range list {
go func() { fmt.Println(&item) }() // Bug: shared address in pre-1.22!
}✅ Correct
for _, item := range list {
val := item
go func() { fmt.Println(&val) }() // Safe: local lexical copy
}Related Go Tutorials & Compiler
Go While Loop Simulation: Conditional and Infinite Loops
Simulate while and infinite loops in Go using the versatile for statement.
Go Break, Continue, and Labeled Loops
Control loop execution with break, continue, and labeled loop escapes.
Go Slices: append, make, copy, and Slicing Operations
Master dynamic slices in Go with make, append, copy, length, and capacity.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.