Jump out of nested loops with goto
Goto can not only replace other statements but also simplify the code. Let's take a look at an example:
package main
import "fmt"
func main() {
// First loop
for i := 0; i < 5; i++ {
// Second loop
for j := 0; j < 5; j++ {
if j == 3 {
goto END
}
fmt.Println(i, j)
}
}
END:
}
In this program, we wrote a nested loop and set it to exit the entire loop when j
is 3.
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
}
}
}
Let's compare the programs using break and goto. We can find that the program using goto is more concise and understandable.
The second program uses two break statements and a check variable to exit.
If there are more nested loops, more break statements need to be added at each level of the loop.