How to break out of nested loops in Go?
use function
package main
import (
"fmt"
)
func getWord() string {
word := ""
for word != "DC" {
for _, i := range "ABCDE" {
for _, j := range "ABCDE" {
word = string(i) + string(j)
fmt.Println(word)
if word == "DC" {
return word
}
}
}
}
return word
}
func main(){
word := getWord()
}
Edit: thanks to @peterSO who points on some mistakes in the details and provides this playground https://play.golang.org/p/udcJptBW9pQ
Use break {label}
to break out of any loop as nested as you want. Just put the label before the for
loop you want to break out of. This is fairly similar to the code that does a goto {label}
but I think a tad more elegant, but matter of opinion I guess.
package main
func main() {
out:
for i := 0; i < 10; i++ {
for j := 0; j < 10; j++ {
if i + j == 20 {
break out
}
}
}
}
More details: https://www.ardanlabs.com/blog/2013/11/label-breaks-in-go.html