In Rust, theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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 thebreak 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
loopor labeled block expression is inferred from the type of the expression passed tobreak. - Type Homogeneity: If a single construct contains multiple
breakstatements, everybreakmust yield a value of the exact same type. - Construct Restriction: Yielding a value via
breakis supported by theloopkeyword and labeled blocks. It is a compilation error to attempt to return a value usingbreakinsidewhile,while let, orforloops. 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 unnestedloopdoes 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, theloop evaluates to an i32, which is bound to result.
break can be combined with a loop label to yield a value from an inner loop directly to the assignment of an outer loop.
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.
Master Rust with Deep Grasping Methodology!Learn More





