Go•Loops
Go While Loop Simulation: Conditional and Infinite Loops
Learn how Go expresses while loops using for condition and infinite server loops with for {}.
Syntax
for condition {}
for {} // Infinite loop
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| for condition | Loop Pattern | Replaces while in C/Java. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import "fmt"
func main() {
countdown := 3
fmt.Println("--- Rocket Countdown ---")
// While-style loop in Go
for countdown > 0 {
fmt.Printf("T-minus %d...\n", countdown)
countdown--
}
fmt.Println("Liftoff! 🚀")
// Controlled loop
power := 1
steps := 0
for power < 50 {
power *= 2
steps++
}
fmt.Printf("\nDoubled %d times to reach %d\n", steps, power)
}Expected Output:
--- Rocket Countdown --- T-minus 3... T-minus 2... T-minus 1... Liftoff! 🚀 Doubled 6 times to reach 64
How It Works: Step-by-Step
- Lines 8-11: for countdown > 0 executes body while condition is true.
- Lines 16-19: Doubles power until reaching or exceeding 50.
Key Concepts
- Go deliberately omitted while and do-while to keep the language keyword count small.
- for condition {} provides the exact behavior of while.
Common Mistake: Trying to write while (cond) in Go
while is not a keyword in Go; attempting to use it causes a compile error.
❌ Incorrect
while (x > 0) {} // Compile Error: undefined: while✅ Correct
for x > 0 {} // Idiomatic GoRelated Go Tutorials & Compiler
Go Unified For Loop: Traditional, While-Style, and Range Iteration
Master Go unified for loop (the only looping keyword in Go), implementing 3-component counters, while-style conditions, infinite loops, and range iteration.
Go Break, Continue, and Labeled Loops
Control loop execution with break, continue, and labeled loop escapes.
Go If Statements with Inline Variable Initialization and Scope Limiting
Master Go if statements with compact inline variable initialization (if init; condition), keeping variables tightly scoped to branch blocks.
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.