Go:Go Break, Continue, and Labeled Loops
Go•Loop Control

Go Break, Continue, and Labeled Loops

break exits the loop; continue advances to the next iteration. Labeled breaks can escape outer loops.

Syntax

if condition { break } if condition { continue }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
breakKeywordTerminates loop execution.
continueKeywordSkips remainder of current iteration.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import "fmt"

func main() {
    packetIds := []int{101, 102, -1, 104, 999, 106}

    fmt.Println("Processing packets:")
    for _, id := range packetIds {
        if id < 0 {
            fmt.Printf("  [SKIP] Glitch packet ID: %d\n", id)
            continue
        }
        if id == 999 {
            fmt.Println("  [HALT] Sentinel ID 999 reached. Terminating.")
            break
        }
        fmt.Printf("  [OK] Processed packet ID: %d\n", id)
    }
}
Expected Output:
Processing packets:
  [OK] Processed packet ID: 101
  [OK] Processed packet ID: 102
  [SKIP] Glitch packet ID: -1
  [OK] Processed packet ID: 104
  [HALT] Sentinel ID 999 reached. Terminating.

How It Works: Step-by-Step

  • Lines 10-13: continue skips negative packet ID.
  • Lines 14-17: break terminates iteration upon ID 999.

Key Concepts

  • continue immediately moves to next sequence element.
  • break can be used with loop labels to break out of nested loops cleanly.

Common Mistake: Using break inside a switch that is inside a for loop

In Go, break inside a switch breaks out of the switch, NOT the enclosing for loop. Use a labeled break.

❌ Incorrect
for { switch x { case 1: break; } } // Breaks only switch!
✅ Correct
Loop: for { switch x { case 1: break Loop; } }

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler