By default, the break and continue keywords apply to the for loop that directly contains them. What if you have nested for loops and want to exit or skip over an iterator of an outer loop? Let’s look at an example.
You’re going to modify the earlier string-iterating program to stop iterating through a string as soon as it hits a letter “l.” You can run the code in Example 3-19 on The Go Playground.
Example 3-19. Labels
func main() {
samples := []string{"hello", "apple_π!"}
outer:
for _, sample := range samples {
for i, r := range sample {
fmt.Println(i, r, string(r))
if r == 'l' {
continue outer
}
}
fmt.Println()
}
}
Notice that go fmt indents the label outer to the same level as the surrounding function. Labels are always indented to the same level as the braces for the block. This makes them easier to notice. Running the program gives the following output:
0 104 h
1 101 e
2 108 l
0 97 a
1 112 p
2 112 p
3 108 l
Nested for loops with labels are rare. They are most commonly used to implement algorithms similar to the following pseudocode:
outer:
for _, outerVal := range outerValues {
for _, innerVal := range outerVal {
// process innerVal
if invalidSituation(innerVal) {
continue outer
}
}
// here we have code that runs only when all of the
// innerVal values have been successfully processed
}