DEV Community

Teruo Kunihiro
Teruo Kunihiro

Posted on

Continue goto in Golang

#go

Sometimes We need to go out from loops or don't want to execute unnecessary part in the loop.
At that time, we use continue or break.

  • break makes out from the inner the loop.
  • continue makes not to execute after this line

But in nest loop, that'll be complicated like this

list := []int{1,2,3,4,5,6,7,8,9,4,5,3,2,1}

anothers := []int{5,4,3,}
for _, item := range list {
    found := false
    for _, another := range anothers {
        if another == item {
            found = true
            break
        }

    }
    if found {
        continue;
    }
    fmt.Println("bingo", item)
}
Enter fullscreen mode Exit fullscreen mode

https://play.golang.org/p/7Q0UMjVHcF-

Ya, of course it's a little bit ugly.

So you can try to change cleaner with goto

list := []int{1,2,3,4,5,6,7,8,9,4,5,3,2,1}

anothers := []int{5,4,3,}
LabelLabel:
for _, item := range list {
    for _, another := range anothers {
        if another == item {
            continue LoopLabel
        }
    }
    fmt.Println("bingo", item)
}

Enter fullscreen mode Exit fullscreen mode

https://play.golang.org/p/AB6ASJaL7TR

continue Loop goes out to LoopLabel loop, it's the outer loop, not the inner loop.

Then it's cleaner than previous one. So you can use goto in nested loops as continue .

Top comments (0)