DEV Community

Teruo Kunihiro
Teruo Kunihiro

Posted on

4

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 .

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay