Go Break and Continue

Break and continue control the flow inside loops. Break exits the loop immediately. Continue skips the current iteration and moves to the next one. Both work with for loops and switch statements.

Break Statement

Break stops the loop entirely and jumps to the code after the loop.

package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i == 5 {
            break
        }
        fmt.Println(i)
    }
    fmt.Println("Loop ended")
}

Output:

1
2
3
4
Loop ended

Break Flow Diagram

i=1 → print 1 → continue loop
i=2 → print 2 → continue loop
i=3 → print 3 → continue loop
i=4 → print 4 → continue loop
i=5 → break ─────────────────► exits loop immediately
                                "Loop ended" prints

Continue Statement

Continue skips the rest of the current iteration and moves directly to the next one.

package main

import "fmt"

func main() {
    for i := 1; i <= 6; i++ {
        if i == 4 {
            continue
        }
        fmt.Println(i)
    }
}

Output:

1
2
3
5
6

The number 4 is skipped. The loop continues with 5 and 6.

Continue Flow Diagram

i=1 → print 1
i=2 → print 2
i=3 → print 3
i=4 → continue ──► skip print, go to i=5
i=5 → print 5
i=6 → print 6

Break in Nested Loops

Break inside a nested loop only exits the innermost loop it belongs to.

package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if j == 2 {
                break // only breaks the inner loop
            }
            fmt.Printf("i=%d j=%d\n", i, j)
        }
    }
}

Output:

i=1 j=1
i=2 j=1
i=3 j=1

Labeled Break – Exit an Outer Loop

Go supports labels to break out of a specific outer loop. Attach a label before the loop and use it with break.

package main

import "fmt"

func main() {
outer:
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if i == 2 && j == 2 {
                break outer // exits the outer loop
            }
            fmt.Printf("i=%d j=%d\n", i, j)
        }
    }
    fmt.Println("Done")
}

Output:

i=1 j=1
i=1 j=2
i=1 j=3
i=2 j=1
Done

Break vs Continue Summary

KeywordActionUse Case
breakExits the loop entirelyStop when a target is found
continueSkips the current iterationSkip unwanted values
break labelExits the labeled outer loopEscape deeply nested loops

Key Points

  • break stops the loop immediately and moves to the code after it
  • continue skips the rest of the current iteration and moves to the next
  • In nested loops, break only exits the innermost loop
  • Labels allow break and continue to target a specific outer loop

Leave a Comment