0
0
GoHow-ToBeginner · 3 min read

How to Use Labeled Break in Go: Syntax and Examples

In Go, you use a labeled break to exit from an outer loop directly by placing a label before the loop and using break followed by that label. This helps you stop nested loops without extra flags or complicated logic.
📐

Syntax

A labeled break in Go uses a label placed before a loop, followed by break and the label name to exit that loop immediately.

Example parts:

  • Label: A name followed by a colon before the loop.
  • break Label: Stops the loop with that label.
go
LabelName:
for i := 0; i < 5; i++ {
    for j := 0; j < 5; j++ {
        if someCondition {
            break LabelName
        }
    }
}
💻

Example

This example shows how to use a labeled break to exit both inner and outer loops when a condition is met.

go
package main

import "fmt"

func main() {
OuterLoop:
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            fmt.Printf("i=%d, j=%d\n", i, j)
            if i*j >= 4 {
                break OuterLoop
            }
        }
    }
    fmt.Println("Exited loops")
}
Output
i=1, j=1 i=1, j=2 i=1, j=3 i=2, j=1 i=2, j=2 Exited loops
⚠️

Common Pitfalls

Common mistakes when using labeled break include:

  • Forgetting to place the label before the correct loop.
  • Using break without a label inside nested loops only exits the innermost loop.
  • Using labels that are not unique or confusing names.

Always ensure the label is clear and placed exactly before the loop you want to break.

go
package main

import "fmt"

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

// Correct way:
// OuterLoop:
// for i := 1; i <= 3; i++ {
//     for j := 1; j <= 3; j++ {
//         if i*j >= 4 {
//             break OuterLoop
//         }
//         fmt.Printf("i=%d, j=%d\n", i, j)
//     }
// }
Output
i=1, j=1 i=1, j=2 i=1, j=3 i=2, j=1 Done
📊

Quick Reference

Labeled break cheat sheet:

  • LabelName: Place before the loop you want to break.
  • break LabelName exits that labeled loop immediately.
  • Use labeled break to exit nested loops cleanly.
  • Labels must be unique within the function.

Key Takeaways

Use a label before a loop and break Label to exit that loop from inside nested loops.
Labeled break helps avoid complex flags or conditions to stop multiple loops.
Without a label, break only exits the innermost loop.
Place labels clearly and use unique names to avoid confusion.
Labeled break improves code readability when breaking out of nested loops.