×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Break Statement

Last Updated : July 19, 2025

In Go, the break statement is used to terminate the execution of a loop or switch statement prematurely.

Using break in Loops

You can use break inside for, for-range, and nested loops to exit the loop when a specific condition is met.

Example

This example breaks out of a loop when the counter reaches 5:

package main
import "fmt"

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

When you run the above code, the output will be:

1
2
3
4

Using break in a for-range Loop

The break statement can also be used to stop iterating over elements of a slice or map once a certain condition is met.

Example

This example iterates through a slice of numbers and breaks when it encounters a negative number:

package main
import "fmt"

func main() {
    numbers := []int{10, 20, 30, -5, 40, 50}

    for _, num := range numbers {
        if num < 0 {
            fmt.Println("Encountered a negative number, breaking loop.")
            break
        }
        fmt.Println(num)
    }
}

When you run the above code, the output will be:

10
20
30
Encountered a negative number, breaking loop.

Using break in Nested Loops

When using nested loops, a break will only exit the innermost loop unless you use labels.

Example

This example breaks the inner loop but continues the outer loop:

package main
import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if j == 2 {
                break
            }
            fmt.Printf("i=%d, j=%d\n", i, j)
        }
    }
}

When you run the above code, the output will be:

i=1, j=1
i=2, j=1
i=3, j=1

Using Labeled break

To break out of an outer loop from within an inner loop, you can use a labeled break.

Example

This example exits both loops when a specific condition is met:

package main
import "fmt"

func main() {
outer:
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if i*j > 4 {
                break outer
            }
            fmt.Printf("i=%d, j=%d\n", i, j)
        }
    }
}

When you run the above code, the output will be:

i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2

Exercise

Select the correct answer for each question about the break statement in Go.

  1. What does the break statement do in Go?
  2. What happens when you use break inside a nested loop without a label?
  3. Which keyword is used to break out of an outer loop in nested loops?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.