In this tutorial you will learn about the Go Break Statement and its application with practical example.
Go Break Statement
In Go, break statement gives you way to break or terminate the execution of innermost “for”, “switch”, or “select” statement that containing it, and transfers the execution to the next statement following it.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package main import "fmt" func main() { var count = 0 fmt.Println("W3Adda - Go break statement.") for count <= 10 { count++ if (count == 5) { break } fmt.Printf("Inside loop %d\n", count) } fmt.Println("Out of loop") } |
In this above program, the variable count is initialized as 0. Then a for loop is executed as long as the variable count is less than 10.
Inside the while loop, the count variable is incremented by 1 with each iteration (count = count + 1).
Next, we have an if statement that checks the variable count is equal to 5, if it return TRUE causes loop to break or terminate.
Within the loop there is a printf() statement that will execute with each iteration of the for loop until the loop breaks.
Then, there is a final println() statement outside of the for loop.
When we run this code, our output will be as follows –
Output:-
Go Labeled break
The standard unlabeled break statement is used to terminates the nearest enclosing statement. In GoLang, there is another form of break (labeled break) statement is used to terminate specified “for”, “switch”, or “select” statement. In GoLang, Label is an identifier which is followed by a colon (:) sign, for example abc:, test:.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package main import "fmt" func main() { var count = 0 fmt.Println("W3Adda - Go labeled break statement.") outer: for count <= 10 { count++ if (count == 5) { break outer } fmt.Printf("Inside loop %d\n", count) } fmt.Println("Out of loop") } |
Here, when count == 5 expression is evaluated to true, break outer is executed which terminates the loop marked with label outer:.
Output:-