← Back to Go Course | Chapter 3: Control Flow | Lesson 6 of 7

break and continue

break tells a loop to stop completely, while continue tells it to skip the rest of this lap and go straight to the next one.

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

markup
package main

import "fmt"

func main() {
	for i := 0; i < 10; i++ {
		if i == 4 {
			break
		}
		fmt.Println(i)
	}
}

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

markup
package main

import "fmt"

func main() {
	for i := 0; i < 6; i++ {
		if i%2 == 0 {
			continue
		}
		fmt.Println("odd:", i)
	}
}

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

markup
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)
		}
	}
}

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

markup
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)
		}
	}
}
Common Mistakes
  1. Using break inside a switch that's nested in a loop, expecting it to exit the loop, when it actually only exits the switch.
  2. Forgetting labeled break/continue exist, and reaching for goto or a boolean flag variable to escape nested loops instead.
  3. Placing continue after code that should always run each iteration, accidentally skipping cleanup logic meant to execute every time.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.