Labelled break and continue help you control loops more precisely by jumping out of or continuing specific loops when you have nested loops.
Labelled break and continue in Go
labelName: for condition { for condition { if someCondition { break labelName // or continue labelName } } }
The label must be placed before the loop you want to control.
Use break labelName to exit the labelled loop completely.
Use continue labelName to continue the next iteration of the labelled loop.
outer: for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if i == 1 && j == 1 { break outer } fmt.Println(i, j) } }
outer: for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if j == 1 { continue outer } fmt.Println(i, j) } }
This program multiplies i and j in nested loops. When the product is greater than 4, it breaks out of the outer loop completely.
package main import "fmt" func main() { outer: for i := 1; i <= 3; i++ { for j := 1; j <= 3; j++ { if i*j > 4 { break outer } fmt.Printf("%d * %d = %d\n", i, j, i*j) } } }
Labels must be unique within the function.
Label names should be short and descriptive to keep code clear.
Using labelled break and continue can simplify nested loop control but avoid overusing them to keep code readable.
Labelled break and continue let you jump out of or continue specific loops in nested loops.
They help avoid extra variables and complex logic for nested loops.
Use labels carefully to keep your code easy to understand.