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 break keyword in Rust is a control flow expression used to immediately terminate the execution of the innermost enclosing loop, while, for construct, or a targeted labeled block expression. When evaluated, control is unconditionally transferred to the statement immediately following the terminated construct.

Basic Loop Syntax

By default, an unannotated break halts the current iteration and exits the closest enclosing loop.
loop {
    break; // Execution jumps to the end of this loop block
}

Labeled Block Expressions

Since Rust 1.65, break can be used to terminate regular block expressions that are annotated with a label. Unlike loops, breaking out of a non-loop block strictly requires the label to be specified in the break statement.
'block: {
    break 'block; // Execution jumps to the end of this labeled block
}

Returning Values via break

In Rust, loop constructs and labeled block expressions can evaluate to a value. The break statement accepts an optional expression payload to return a value from these constructs. Note: This mechanic is limited to loop and labeled blocks. The while and for constructs cannot return values via break and always evaluate to the unit type ().
let loop_result: i32 = loop {
    break 42; // Terminates the loop and yields '42'
};

let block_result: i32 = 'block: {
    break 'block 99; // Terminates the block and yields '99'
};

Control Flow Labels

Rust supports control flow labels, denoted by a single quote followed by an identifier ('label). Labels allow break to bypass the default behavior of targeting the innermost loop, enabling the termination of specific outer loops within a nested structure.
'outer: for i in 0..10 {
    'inner: loop {
        break 'outer; // Terminates the 'outer for loop, bypassing 'inner
    }
}

Combining Labels and Values

When working with nested loop or labeled block expressions, break can simultaneously target a specific label and return a value to that construct’s binding. The syntax requires the label to precede the value expression.
let nested_result = 'outer: loop {
    loop {
        break 'outer 100; // Terminates 'outer and yields 100 to 'nested_result'
    }
};

Type System Implications

  • Expression Type: The break expression itself represents a divergence in control flow. Therefore, it evaluates to the never type (!). This allows break to be used in contexts that expect a specific type, as ! can be coerced into any type.
  • Construct Type: If a loop or labeled block contains multiple break statements that return values, the compiler enforces that all yielded expressions must resolve to the same type. If break is used without a payload, the construct evaluates to the unit type ().
Master Rust with Deep Grasping Methodology!Learn More