How to Use break in Go: Syntax and Examples
In Go, the
break statement is used to immediately exit a loop or a switch statement. When break is executed, the program stops the current loop iteration and continues with the code after the loop.Syntax
The break statement can be used inside for, switch, and select blocks to exit them immediately.
Basic syntax:
break
You can also use break with a label to exit an outer loop:
break LabelName
go
for i := 0; i < 5; i++ { if i == 3 { break } fmt.Println(i) }
Example
This example shows how break stops a loop when a condition is met, printing numbers from 0 to 2 only.
go
package main import "fmt" func main() { for i := 0; i < 5; i++ { if i == 3 { break } fmt.Println(i) } fmt.Println("Loop ended") }
Output
0
1
2
Loop ended
Common Pitfalls
One common mistake is expecting break to exit multiple nested loops without using labels. By default, break only exits the innermost loop.
To exit an outer loop, use a labeled break.
go
package main import "fmt" func main() { OuterLoop: for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if i == 1 && j == 1 { break OuterLoop // exits both loops } fmt.Printf("i=%d, j=%d\n", i, j) } } fmt.Println("Exited loops") }
Output
i=0, j=0
i=0, j=1
i=0, j=2
i=1, j=0
Exited loops
Quick Reference
| Usage | Description |
|---|---|
| break | Exits the innermost loop or switch immediately |
| break LabelName | Exits the loop or switch with the specified label |
| Used in for, switch, select | Controls flow by stopping loops or switch cases early |
Key Takeaways
Use
break to exit loops or switch statements immediately.Without labels,
break only stops the innermost loop.Use labeled
break to exit outer loops in nested structures.Place
break inside loop or switch blocks to control flow clearly.