In Go, the break
statement is used to prematurely exit a loop. It is commonly used to terminate a loop based on a certain condition or to exit a loop when a specific criteria is met. Here are some examples of using the break
statement in Go:
- Breaking out of a loop based on a condition:
for i := 0; i < 10; i++ {
if i == 5 {
break
}
fmt.Println(i)
}
In this example, the loop will iterate from 0 to 9. However, when i
becomes equal to 5, the break
statement is encountered, and the loop is terminated. The output will be:
0
1
2
3
4
- Breaking out of a nested loop:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
fmt.Println(i, j)
if i == 1 && j == 1 {
break
}
}
}
In this example, there is a nested loop structure. When i
is equal to 1 and j
is equal to 1, the break
statement is encountered, causing the inner loop to terminate. The outer loop continues its execution. The output will be:
0 0
0 1
0 2
1 0
1 1
2 0
2 1
2 2
The break
statement provides control over the flow of execution within loops. It allows you to exit a loop prematurely and move on to the next statement after the loop. By strategically placing break
statements, you can implement various conditions and termination criteria in your loops.