Exiting Nested Loops with goto
Exiting nested loops can be cumbersome using break
, as it typically requires additional logic and variables. goto
simplifies this process by allowing direct jumps out of multiple loops.
Example: Using goto
to Exit Nested Loops
- Create a new file named
nested_loop_with_goto.go
:
cd ~/project
touch nested_loop_with_goto.go
- Write the following code:
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ { // Outer loop
for j := 0; j < 5; j++ { // Inner loop
if j == 3 { // Exit condition
goto END // Jump to the "END" label
}
fmt.Println(i, j) // Print the current values of i and j
}
}
END:
}
- The program starts with a nested loop: an outer loop for
i
and an inner loop for j
.
- Inside the inner loop, it checks if
j
equals 3
. If true, the program jumps to the END
label, exiting both loops.
- As a result, the program prints the pairs
(i, j)
only until j
equals 2
.
- Run the program:
go run nested_loop_with_goto.go
- Observe the output:
0 0
0 1
0 2
This approach is much cleaner than using multiple break
statements or flags, especially in deeply nested loops.
If we use the break statement to implement this program, as shown below:
package main
import "fmt"
func main() {
// Check variable
var check = false
// First loop
for i := 0; i < 5; i++ {
// Second loop
for j := 0; j < 5; j++ {
if j == 3 {
// Exit the second loop
check = true
break
}
fmt.Println(i, j)
}
// Determine whether to exit the first loop
if check == true {
break
}
}
}