Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The continue statement in Go is a control flow directive used exclusively within for loops to terminate the execution of the current iteration. When a continue statement is executed, it immediately halts execution of the remaining statements in the current loop body and advances control to the next iteration of the loop.

Syntax

continue
// or
continue LabelName

Execution Mechanics

The exact behavior of the continue statement depends on the variant of the for loop in which it is invoked:
  1. Standard for loop (for init; condition; post): Control flow jumps directly to the post statement (e.g., i++), executes it, and then evaluates the condition to determine if the loop should proceed.
  2. Condition-only for loop (for condition): Control flow jumps directly to the evaluation of the loop condition.
  3. for range loop: Control flow jumps to the assignment of the next sequence values (index/key and value) and proceeds with the next iteration.
  4. Infinite loop (for {}): Control flow jumps directly back to the beginning of the loop body.
package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        // Statement A
        condition := (i == 2)
        if condition {
            continue // Bypasses Statement B; jumps directly to i++
        }
        // Statement B (Skipped when condition is true)
        fmt.Println(i)
    }
}

Labeled continue

Go supports labeled continue statements, which are used to manage control flow within nested loops. By default, an unlabeled continue applies only to the innermost enclosing for loop. By appending a label, you can explicitly instruct the program to continue the iteration of a specific outer loop. A label is declared using an identifier followed by a colon (:) and must be positioned immediately preceding the target for loop.
package main

import "fmt"

func main() {
OuterLoop:
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            condition := (j == 1)
            if condition {
                // Halts the inner loop's current iteration.
                // Jumps directly to i++ of the OuterLoop.
                continue OuterLoop 
            }
            fmt.Printf("i=%d, j=%d\n", i, j)
        }
    }
}

Lexical Constraints

  • A continue statement must be lexically nested inside a for loop. Using it outside of a loop structure results in a compile-time error (continue is not in a loop).
  • When using a labeled continue, the specified label must be defined in the same function and must directly precede a for loop that encloses the continue statement. It cannot be used to jump to arbitrary labels in the code.
Master Go with Deep Grasping Methodology!Learn More