break and continue
Using break
break immediately stops the nearest enclosing for loop, skipping any remaining iterations, and execution continues with the code right after the loop.
Example: Using break
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i == 4 {
break
}
fmt.Println(i)
}
}
Login to try C/C++/Java/PHP code in the editor
Using continue
continue skips the rest of the current iteration's body and jumps straight to the loop's next iteration (running the post statement first, in a three-part for loop).
Example: Using continue
package main
import "fmt"
func main() {
for i := 0; i < 6; i++ {
if i%2 == 0 {
continue
}
fmt.Println("odd:", i)
}
}
Login to try C/C++/Java/PHP code in the editor
break Inside switch
Because switch also accepts break, a break statement written inside a switch that itself sits inside a loop only exits the switch -- it does not also exit the loop. This surprises people used to languages where break always targets the nearest loop.
Note: Remember: a bare break in a switch stops the switch, not the loop it's inside.
Example: break Inside switch
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
switch i {
case 1:
break // only exits the switch, loop continues
default:
fmt.Println("processing", i)
}
}
}
Login to try C/C++/Java/PHP code in the editor
Labeled break and continue
To break or continue an outer loop from inside a nested one, Go lets you label the outer loop and reference that label, giving precise control without resorting to goto or flag variables.
Example: Labeled break and continue
package main
import "fmt"
func main() {
Outer:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if j == 1 {
continue Outer
}
fmt.Println(i, j)
}
}
}
Login to try C/C++/Java/PHP code in the editor
- Using break inside a switch that's nested in a loop, expecting it to exit the loop, when it actually only exits the switch.
- Forgetting labeled break/continue exist, and reaching for goto or a boolean flag variable to escape nested loops instead.
- Placing continue after code that should always run each iteration, accidentally skipping cleanup logic meant to execute every time.
- break immediately exits the nearest enclosing for loop (or switch/select).
- continue skips the rest of the current iteration and moves to the loop's next iteration.
- A labeled break or continue can target an outer loop from inside a nested one.
- break inside a switch exits the switch, not any surrounding loop -- use a label if you need to exit the loop.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: