Go Language Break Statement
The break statement in Go language is used for the following purposes:
To exit a loop and proceed to the statement following the loop.
In a switch statement, break is used to exit after executing a case.
In nested loops, break can be used with a label to specify which loop to exit.
Syntax
The syntax for the break statement is as follows:
break;
The flowchart for the break statement is shown below:
Example
Break the loop when the variable a is greater than 15:
Example
package main
import "fmt"
func main() {
/* Define local variables */
var a int = 10
/* for loop */
for a < 20 {
fmt.Printf("Value of a: %d\n", a)
a++
if a > 15 {
/* Break the loop using break statement */
break
}
}
}
The output of the above example is:
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
The following example demonstrates the use of labels and no labels in nested loops:
Example
package main
import "fmt"
func main() {
// Without label
fmt.Println("---- break ----")
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
break
}
}
// With label
fmt.Println("---- break label ----")
re:
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
break re
}
}
}
The output of the above example is:
---- break ----
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11
---- break label ----
i: 1
i2: 11