Controlling nested loops with labels in Go
Loops can be nested. When you use break
inside a nested loop, it will jump out of the current loop; continue
will continue the current loop.
If we want to break out of both loops from inside the inner loop, we can use a label.
A label in Go is simply a way of giving a name to a particular location in the code, so that we can refer to it later. The syntax for a label is just the name of the label followed by a colon.
1outer:
2 for x := 0; x < 10; x++ {
3 for y := 0; y < 10; y++ {
4 fmt.Println(x, y)
5 if y == 5 {
6 break outer
7 }
8 }
9 }
If we wanted to continue the outer loop instead of exiting it, we could have written continue outer
.
The goto
keyword will simply jump directly to the specified label.
References
- John Arundel, For the Love of Go
#programming #nested #loops #range #break #init #goto #flow #assignments #continue #labels #repeat #for #infinite #statement #golang #post