Skip to main content
In Rust, the break keyword can terminate execution of a loop or a labeled block expression and simultaneously yield a value to the surrounding scope. Because these constructs are expressions, they evaluate to a value, and break serves as the mechanism to return that value to the binding context.

Syntax

To return a value, append the expression directly after the break keyword. If breaking from a specific labeled construct, the label must precede the value expression. When assigning the result of a loop or labeled block to a variable via a let statement, the let statement itself must be terminated with a semicolon. However, if the loop or labeled block is used as a trailing expression (e.g., as the implicit return value of a function), no semicolon is required.

Mechanics and Compiler Rules

  • Type Inference: The type of the loop or labeled block expression is inferred from the type of the expression passed to break.
  • Type Homogeneity: If a single construct contains multiple break statements, every break must yield a value of the exact same type.
  • Construct Restriction: Yielding a value via break is supported by the loop keyword and labeled blocks. It is a compilation error to attempt to return a value using break inside while, while let, or for loops. Those constructs inherently evaluate to the unit type ().
  • Labeled Block Requirement: Breaking out of a labeled block always requires the label to be explicitly specified (e.g., break 'block_name value;). In contrast, breaking from an unnested loop does not require a label (e.g., break value;).
  • Unit Type Default: If a construct is broken using break; without an expression, it implicitly yields the unit type ().

Code Examples

Basic Value Yielding In this example, the loop evaluates to an i32, which is bound to result.
Combining with Loop Labels When dealing with nested loops, break can be combined with a loop label to yield a value from an inner loop directly to the assignment of an outer loop.
Yielding from a Labeled Block Since Rust 1.65, break can yield a value from a standard block expression annotated with a label, bypassing the need for a loop construct. The label is mandatory when breaking from a block.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More