Go Break Statement

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:-

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_break_statement

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:-

Here, when count == 5 expression is evaluated to true, break outer is executed which terminates the loop marked with label outer:.

Output:-

go_labeled_break_statement_1

In this tutorial we have learn about the Go Break Statement and its application with practical example. I hope you will like this tutorial.