Go•Loop Control
Go Break, Continue, and Labeled Loops
break exits the loop; continue advances to the next iteration. Labeled breaks can escape outer loops.
Syntax
if condition { break }
if condition { continue }
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| break | Keyword | Terminates loop execution. |
| continue | Keyword | Skips remainder of current iteration. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import "fmt"
func main() {
packetIds := []int{101, 102, -1, 104, 999, 106}
fmt.Println("Processing packets:")
for _, id := range packetIds {
if id < 0 {
fmt.Printf(" [SKIP] Glitch packet ID: %d\n", id)
continue
}
if id == 999 {
fmt.Println(" [HALT] Sentinel ID 999 reached. Terminating.")
break
}
fmt.Printf(" [OK] Processed packet ID: %d\n", id)
}
}Expected Output:
Processing packets: [OK] Processed packet ID: 101 [OK] Processed packet ID: 102 [SKIP] Glitch packet ID: -1 [OK] Processed packet ID: 104 [HALT] Sentinel ID 999 reached. Terminating.
How It Works: Step-by-Step
- Lines 10-13: continue skips negative packet ID.
- Lines 14-17: break terminates iteration upon ID 999.
Key Concepts
- continue immediately moves to next sequence element.
- break can be used with loop labels to break out of nested loops cleanly.
Common Mistake: Using break inside a switch that is inside a for loop
In Go, break inside a switch breaks out of the switch, NOT the enclosing for loop. Use a labeled break.
❌ Incorrect
for { switch x { case 1: break; } } // Breaks only switch!✅ Correct
Loop: for { switch x { case 1: break Loop; } }Related 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 While Loop Simulation: Conditional and Infinite Loops
Simulate while and infinite loops in Go using the versatile for statement.
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.