Edit: You edited you code, so here's the edited answer for that.
To continue the outer loop from the inner (breaking the inner loop and skipping the rest of the outer loop), you have to continue the outer loop.
To address the outer loop with the continue
statement use a label:
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
continue outer
} else {
fmt.Println("j = ", j)
}
}
fmt.Println("The value of i is", i)
}
This will output (try it on the Go Playground):
j = 0
j = 1
Breaking out of loop
j = 0
j = 1
Breaking out of loop
Original answer:
break
always breaks from the innermost loop (more specifically a for
, switch
or select
), so after that the outer loop will continue with its next iteration.
If you have nested loops and from an inner loop you want to break from the outer loop, you have to use labels:
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
break outer
}
fmt.Println("The value of j is", j)
}
}
This will output (try it on the Go Playground):
The value of j is 0
The value of j is 1
Breaking out of loop