notexOPENOverview
Notex/Languages/break and continue
02.09LESSON 09 OF 19 · 2 MIN READ

break and continue

Always free to read

How do you get out of an infinite for loop without using the keyboard or turning off your computer? That’s the job of the break statement. It exits the loop immediately, just like the break statement in other languages. Of course, you can use break with any for statement, not just the infinite for statement.

Note

Go has no equivalent of the do keyword in Java, C, and JavaScript. If you want to iterate at least once, the cleanest way is to use an infinite for lo say you have some Java code that uses a do/while loop:

do {
    // things to do in the loop
} while (CONDITION);

The Go version looks like this:

for {
    // things to do in the loop
    if !CONDITION {
        break
    }
}

Note that the condition has a leading ! to negate the condition from the Java code. The Go code is specifying how to exit the loop, while the Java code specifies how to stay in it.

Go also includes the continue keyword, which skips over the rest of the for loop’s body and proceeds directly to the next iteration. Technically, you don’t need a+continue+ statement. You could write code like Example 3-11.

Example 3-11. Confusing code

for i := 1; i <= 100; i++ {
    if i%3 == 0 {
        if i%5 == 0 {
            fmt.Println("FizzBuzz")
        } else {
            fmt.Println("Fizz")
        }
    } else if i%5 == 0 {
        fmt.Println("Buzz")
    } else {
        fmt.Println(i)
    }
}

But this is not idiomatic. Go encourages short if statement bodies, as left-aligned as possible. Nested code can be difficult to follow. Using a continue statement makes it easier to understand what’s going on. Example 3-12 shows the code from the previous example, rewritten to use continue instead.

Example 3-12. Using continue to make code clearer

for i := 1; i <= 100; i++ {
    if i%3 == 0 && i%5 == 0 {
        fmt.Println("FizzBuzz")
        continue
    }
    if i%3 == 0 {
        fmt.Println("Fizz")
        continue
    }
    if i%5 == 0 {
        fmt.Println("Buzz")
        continue
    }
    fmt.Println(i)
}

As you can see, replacing chains of if/else statements with a series of if statements that use continue makes the conditions line up. This improves the layout of your conditions, which means your code is easier to read and understand.

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K