ProgramGuru

break Statement

Start with Go break Statement

A break statement exits the nearest enclosing for, switch or select statement. It is useful when further work is unnecessary.

What you’ll learn

  • Use break to stop work early.
  • Trace a search loop.
  • Distinguish stopping a loop from ending a function.

Understand the idea

Inside a search loop, you can break as soon as a match appears. Execution then resumes with the first statement after that loop. break does not terminate the entire program.

In nested loops, an unlabeled break stops only the innermost applicable construct. Go also supports labeled breaks when a controlled exit from an outer construct is required.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for breakOnly a match exits early; other values continue the search.Read numberStep 1Compare with 9Step 2Break on matchStep 3Resume after loopStep 4Only a match exits early; other values continue the search.
Only a match exits early; other values continue the search.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	numbers := []int{3, 6, 9, 12}
	for _, number := range numbers {
		if number == 9 {
			fmt.Println("Found 9")
			break
		}
		fmt.Println("Checked", number)
	}
	fmt.Println("Search finished")
}

Output

Checked 3
Checked 6
Found 9
Search finished

Trace what the program does

The loop checks 3 and 6. When it reaches 9, the condition is true, the program prints Found 9 and breaks. It never examines 12; execution continues with Search finished.

Avoid common mistakes

  • break stops a loop; it does not return from the surrounding function.
  • Inside nested loops, remember which loop the unlabeled break affects.

Try it yourself

Change the target to 12. Explain why one more Checked line appears before the match.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What happens after break executes inside a for loop?
Choose one answer. You can try again.

Answer and explanation

Execution continues after the loop

Correct. The loop checks 3 and 6.

What you should remember

You have practiced Go break Statement in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: continue Statement →