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 .

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

đź‘‹ Kindness is contagious

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

Okay