Skip to main content
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.

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.

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 ().

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.

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.

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 ().
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More