Break. 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.
Example. 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.
Part 1 We create a slice of 3 strings, and the string "frog" is the second element in the slice.
Part 3 If an element with the value "frog" is encountered, we exit the loop with a 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
Label. 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.
Part 1 We have a label called "Outer" that is for the top-level for-loop. Each loop iterates over 10 integers.
Part 2 If this condition is true, we 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
Break, return. 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.