Question

In order to jump out of inner loop, and continue with the outer loop, we could either use continue Label or use break.

Here's an example from http://www.goinggo.net/2013/11/label-breaks-in-go.html

The original post is using the continue Label pattern:

    guestList := []string{"bill", "jill", "joan"}
    arrived := []string{"sally", "jill", "joan"} 

CheckList:
    for _, guest := range guestList {
        for _, person := range arrived {
            fmt.Printf("Guest[%s] Person[%s]\n", guest, person)

            if person == guest {
                fmt.Printf("Let %s In\n", person)
                continue CheckList
            }
        }
    }

The same result could be achieved through using break, as shown here: http://play.golang.org/p/0YUjkdxxRE

guestList := []string{"bill", "jill", "joan"}
arrived := []string{"sally", "jill", "joan"}

for _, guest := range guestList {
    for _, person := range arrived {
        fmt.Printf("Guest[%s] Person[%s]\n", guest, person)

        if person == guest {
            fmt.Printf("Let %s In\n", person)
            break
        }
    }
}

Which way is more idiomatic in Go?

Was it helpful?

Solution

I don't know if there's any widely accepted standard for which to use. Note that these two are not equivalent, however.

Take:

for _,guest := range guestList {
    for _,person := range arrived {
        fmt.Printf("Guest[%s] Person[%s]\n", guest, person)

        if person == guest {
            fmt.Printf("Let %s In\n", person)
            break
        }
    }
    fmt.Println("Superfluous line!")
}

vs

OuterLoop:
for _,guest := range guestList {
    for _,person := range arrived {
        fmt.Printf("Guest[%s] Person[%s]\n", guest, person)

        if person == guest {
            fmt.Printf("Let %s In\n", person)
            continue OuterLoop
        }
    }
    fmt.Println("Superfluous line!")
}

If the break or continue is hit, the former will print "Superfluous Line!", while the latter will not. Which you use largely depends on whether you want code in the outer loop to execute after your inner loop terminates. If no such code exists, then it largely depends on whether you think you'll ever add code there.

Keep in mind what you're saying semantically in the code. One is saying "I would like the outer loop to go to its next iteration (or exit if none exists)". The other is saying "I would like this loop to exit". Overall, I think most people find that code that affects and considers, as much as possible, the most local scope is generally the clearest. For this reason I'd avoid the labelled continue unless it's necessary, but I don't think it's a great holy affront either way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top