0
0
Goprogramming~5 mins

Labelled break and continue in Go

Choose your learning style9 modes available
Introduction

Labelled break and continue help you control loops more precisely by jumping out of or continuing specific loops when you have nested loops.

When you have loops inside loops and want to stop or skip iterations of an outer loop from inside an inner loop.
When you want to avoid complex flags or extra variables to control nested loops.
When you want to improve code readability by clearly showing which loop you are breaking or continuing.
When you want to exit multiple loops at once based on a condition deep inside nested loops.
Syntax
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.

Examples
This breaks out of the outer loop when i and j both equal 1.
Go
outer:
for i := 0; i < 3; i++ {
    for j := 0; j < 3; j++ {
        if i == 1 && j == 1 {
            break outer
        }
        fmt.Println(i, j)
    }
}
This skips to the next iteration of the outer loop when j equals 1.
Go
outer:
for i := 0; i < 3; i++ {
    for j := 0; j < 3; j++ {
        if j == 1 {
            continue outer
        }
        fmt.Println(i, j)
    }
}
Sample Program

This program multiplies i and j in nested loops. When the product is greater than 4, it breaks out of the outer loop completely.

Go
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)
        }
    }
}
OutputSuccess
Important Notes

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.

Summary

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.