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 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 unannotatedbreak 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 nestedloop 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
breakexpression itself represents a divergence in control flow. Therefore, it evaluates to the never type (!). This allowsbreakto be used in contexts that expect a specific type, as!can be coerced into any type. - Construct Type: If a
loopor labeled block contains multiplebreakstatements that return values, the compiler enforces that all yielded expressions must resolve to the same type. Ifbreakis used without a payload, the construct evaluates to the unit type().
Master Rust with Deep Grasping Methodology!Learn More





