Summary: in this tutorial, you will learn how to use the Go break statement to exit a loop prematurely.
Introduction to the Go break statement
In Go, the break statement allows you to exit a loop prematurely:
breakTypically, you terminate the loop based on a condition, therefore, you often use the break with an if statement like this:
if condition {
break
}For example, the following shows how to use the break statement to terminate a loop that finds the first occurrence of the letter o in the string "Hello World":
package main
import "fmt"
func main() {
messages := "Hello World"
for index, value := range messages {
if value == 'o' {
fmt.Printf("The letter o found at the index %d\n", index)
break
}
}
}How it works.
First, declare a message variable and initialize its value to "Hello World":
messages := "Hello World"Second, iterate over each character in the string messages using a for range loop:
for index, value := range messages {Third, display the index of the first occurrence of the letter o and terminate the loop prematurely using the break statement:
if value == 'o' {
fmt.Printf("The letter o found at the index %d\n", index)
break
}If we don’t use the break statement, the for range loop will run till the last character of the string Hello World.
Using Go break statement with a label
The break statement accepts an optional loop label:
break LoopLabelIn practice, you use the break statement with a label when you want to stop inner and outer loops. For example:
package main
import "fmt"
func main() {
matrix := [][] int {
{1, 2, 3},
{4, 5, 6},
{7, 5, 5},
}
target := 5
search:
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[i]); j++ {
if matrix[i][j] == target {
fmt.Printf("Found %d at (%d, %d)\n", target, i, j)
break search
}
}
}
}How it works.
First, declare and initialize a two-dimensional array:
matrix := [][] int {
{1, 2, 3},
{4, 5, 6},
{7, 5, 5},
}Second, declare and initialize a variable that holds a value to search:
target := 5Third, iterate over the elements of the matrix using two for loops to find the number 5:
search:
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[i]); j++ {
if matrix[i][j] == target {
fmt.Printf("Found %d at (%d, %d)\n", target, i, j)
break search
}
}
}Before the loop, we declare the search label for using with the break statement. Inside the loops, when we come across an element with the value 5, we stop both inner and outer loops using the break search statement.
Summary
- Use the
breakstatement to terminate a loop immediately.