Signup/Sign In
PUBLISHED ON: JULY 16, 2021

Break statement in Go

Sometimes, we may want to terminate the execution of a loop immediately without checking the condition. To specifically change the flow of execution, we have the break statement in Go.

In every iteration, a condition has to be checked to see whether the loop should stop. If the exit condition becomes true, the loop is left through the break statement.

A break statement always breaks out of the innermost structure in which it occurs; it can be used in any for-loop (counter, condition, and so on), but also in a switch, or a select statement.

Execution is continued after the ending } of that structure. The following figure explains the break statement.

Consider the diagram shown below as reference:

go break

Now, we know how the break statement works in Go, we can make use of it in a simple Go program.

Example: Break Statement in Go

Consider the example shown below:

package main

import (
	"fmt"
)

func main() {
	fruits := []string{"apple", "banana", "mango", "litchi", "kiwi"}
	for _, fruit := range fruits {
		if fruit == "litchi" {
			break
		}
		fmt.Println("The Current fruit is:", fruit)
	}
    fmt.Println("outer loop")
}


The current fruit is: apple
The current fruit is: banana
The current fruit is: mango
Will print

In the above program, the break statement is implemented inside the range-for loop, and what we are doing is a simple traversal of the slice named fruits and once we match the current slice item to a particular value, in our case, the "litchi", we are terminating the loop and exiting from it. The control will go back to the next statements of expressions after this range-for loop once the loop is terminated.

Example 2: Break Statement in Go

Let's consider one more example of the break statement where we will make use of an infinite loop and will terminate the loop once we have reached a certain limit.

Consider the example shown below

package main

import (
	"fmt"
)
func main() {
	var count int
	for {
		count++
		fmt.Println("The count is:", count)
		if count == 10 {
			break
		}
	}
	fmt.Println("Loop ended")
}


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9
The count is: 10
Loop ended

Conclusion

In this tutorial, we learned what break statements are in Go, how to use them and how do they actually work.



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.