Sometimes in Go programs we need to exit a loop early, without running any further iterations. The break
statement can be used to terminate the loop.
With a break
with no label, we can exit the immediately enclosing loop. With a label, it is possible to exit multiple nested enclosing loops at once.
This program loops over elements in a slice with a for
-loop. The string
"frog" is considered a sentinel element, and we terminate the loop with a break
when it is encountered.
string
"frog" is the second element in the slice.for-range
loop, we enumerate the elements of the slice and print them to the console.break
statement.package main
import "fmt"
func main() {
// Part 1: create a slice of 3 strings.
animals := []string{"bird", "frog", "dog"}
// Part 2: loop over the slice of strings, and print each string element.
for _, animal := range animals {
fmt.Println(animal)
// Part 3: if the string is "frog", break the loop.
if animal == "frog" {
break
}
}
}bird
frog
With a label, it is possible to use the break
keyword to stop executing a loop that contains the enclosing loop. We do not need to set boolean flags and have multiple break
statements.
for
-loop. Each loop iterates over 10 integers.break
both the inner and the outer loop with a labeled break
statement.package main import "fmt" func main() { // Part 1: specify a label for the outer loop, and then use 2 nested loops. Outer: for i := range 10 { for b := range 10 { // Part 2: if the inner variable is 5, terminate both the inner and outer loops with a break. if b == 5 { break Outer } fmt.Println(i, b) } } }0 0 0 1 0 2 0 3 0 4
If the loop we want to break
is in a separate method, we can often use a return statement instead of a break
statement.
package main import "fmt" func Example() { word := "abc" for _, r := range word { if r == 'c' { // The return keyword could be used instead of break here. break } fmt.Println(r) } } func main() { Example() }97 98
With the break
keyword, we have a standard way to exit the enclosing loop in a Go program. Other keywords, such as continue or return, can fill similar requirements.