Go break statement
Go break statement is used to break out of its immediate surrounding loop.
Go break statement can be used to break a for loop or to break a switch statement.
In this tutorial, we will learn how to use a break statement to break for loop or a switch statement.
Syntax
The syntax of break statement is
break
Examples
Break For Loop
In the following program, we will break the for loop when the value of x is equal to 5.
example.go
package main
import "fmt"
func main() {
var i int = 0
for i < 50 {
if i == 5 {
break
}
fmt.Println(i)
i = i + 1
}
}
Output
0
1
2
3
4
Without break statement, for loop would have executed until i
is 50. But, break statement has broken the for loop when i == 5
.
Break in Nested For Loop
In this example, we write a nested for loop, and use break statement to break inner loop. break statement can break only the loop it is immediate to it.
example.go
package main
import "fmt"
func main() {
var n int = 5
var i int = 0
for i < n {
var k int = 0
for k < n {
fmt.Print("* ")
if i == k {
break
}
k = k + 1
}
fmt.Println()
i = i + 1
}
}
Output
*
* *
* * *
* * * *
* * * * *
Break in Switch Statement
In this example, we write a nested for loop, and use break statement to break inner loop. break statement can break only the loop it is immediate to it.
example.go
package main
import "fmt"
func main() {
var n int = 0
var today int = 2
switch today {
case 1:
fmt.Printf("Today is Monday")
fmt.Printf("Hello World")
case 2:
fmt.Printf("Today is Tuesday")
if n == 0 {
break
}
fmt.Printf("Hello World")
case 3:
fmt.Printf("Today is Wednesday")
fmt.Printf("Hello World")
default:
fmt.Printf("Hello World")
}
}
Output
Today is Tuesday
Conclusion
In this Golang Tutorial, we learned about break statement, and how to use it to break a for loop or switch statement, with the help of examples.