Loops -- Expressions and Labels
A value-producing loop can return a value through break. for and while are statement loops: use a bare break to exit them.
The snippets below illustrate individual constructs. A snippet referring to application names such as generateNext, process, or Token is a fragment, not a standalone program. For complete counted-loop examples, see Integer ranges.
Loops as Expressions
A value-producing loop can yield a value via break:
loop with Break Value
// loop is the primary way to compute with early exit
let result = loop {
let candidate = generateNext()
if isGood(candidate) {
break candidate // loop returns this value
}
if attempts > 1000 {
break defaultValue // fallback return
}
}
// result is the value from whichever break executedfor and while are statement loops
Use break without a value in a for or while. The current type checker rejects break value in a statement loop. To retain a result from a search, store it in a mutable Option and break without a value, or return from the function. A statement loop does not implicitly produce Some or None.
Labeled Blocks
Labels allow naming a block or loop so break and continue can target a specific scope:
Labeled Block Expressions
let value = 'outer: {
let x = compute()
if x < 0 {
break 'outer 0 // break out of 'outer with value 0
}
let y = 'inner: {
if x > 100 {
break 'inner x / 2
}
break 'inner x * 2
}
break 'outer y + 1
}Labeled Loops
'search: for row in 0..gridHeight {
for col in 0..gridWidth {
if grid[row][col] == target {
$println(f"Found at ({row}, {col})")
break 'search // breaks the OUTER loop, not just the inner
}
}
}continue with Labels
'outer: for i in 0..10 {
for j in 0..10 {
if i * j > 50 {
continue 'outer // skip rest of inner loop AND advance outer loop
}
process(i, j)
}
}Loop Forms Reference
for -- Iteration
for index in 0..10 { } // 0 through 9
for index in 0..=10 { } // 0 through 10
let! index = 0;
while index < 10 {
$println(index); // 0, 2, 4, 6, 8
index += 2;
}Iteration follows the selected IntoIterator.iter() and Iterator.next() contract. Do not infer element ownership from the absence of an & before the collection. For example, the prelude's Vec<T> iterator yields &T:
let! values = Vec.new<i32>();
values.push(10);
values.push(20);
for value in values { $println(*value); }
$println(values.len()); // the vector still owns its two elementsA mutable borrow uses &values!, not &!values. The ability to borrow a collection mutably does not itself establish that it has a mutable iterator. Use the collection's documented mutable accessors when changing elements. Map iteration similarly follows its declared item type, typically borrowed key/value pairs; do not assume a generic enumerate() adapter exists.
while -- Condition-Based
while condition {
// body
}
// While-let pattern
while let Some(item) = queue.pop() {
process(item)
}loop -- Infinite Loop
loop {
// runs until break, return, or panic
if done {
break
}
}Loop Control Flow
| Expression | Behavior |
|---|---|
break | Exit the innermost loop immediately |
break value | Exit a value-producing loop with a value |
break 'label | Exit the named loop |
break 'label value | Yield from a value-producing loop or labelled block |
continue | Skip to next iteration of innermost loop |
continue 'label | Skip to next iteration of named loop |
Loop Return Types
A value-producing loop takes its result type from its compatible break values and its surrounding type context. for and while are statement loops, so do not use break value to produce an Option from them.
let answer: i32 = loop {
break 5
}Common Patterns
Find First Match
For a bounded search, keep an explicit Option or return from a function on a match. If the loop finishes without finding a match, return None explicitly. This makes the no-match path visible rather than relying on an implicit loop result.
Bounded Retry
Count attempts separately from any delay policy. This helper makes at most maxAttempts calls, returns immediately after success, and preserves the last operation error on exhaustion:
fn retry<T, E>(operation: fn(): Result<T, E>, maxAttempts: i32): Option<Result<T, E>> {
if maxAttempts <= 0 { return None; }
let! attempt = 0;
loop {
attempt += 1;
match operation() {
Ok(value) => { return Some(Ok(value)); },
Err(error) => {
if attempt == maxAttempts { return Some(Err(error)); }
},
};
}
}This is a helper definition: supply the operation at the call site. None means no attempt was allowed. If a real operation has side effects, retry it only when its contract permits repetition. Backoff, cancellation, and a total deadline are separate policies; comparing an exponentially increasing delay to an attempt limit does not count retries correctly.
State Machine with Labeled Blocks
fn parseStateMachine(tokens: Span<Token>): Result<Ast, ParseError> {
let! state = State.Initial
return 'parse: {
for token in tokens {
state = match (state, token) {
(Initial, OpenBrace) => InBlock,
(InBlock, Identifier(name)) => {
// ... handle identifier
InBlock
},
(InBlock, CloseBrace) => break 'parse Ok(ast),
(_, unexpected) => break 'parse Err(ParseError.new(unexpected)),
}
}
break 'parse Err(ParseError.new("Unexpected end of input"))
}
}Best Practices
- Use
loopwithbreak valuefor complex initialization or search logic that doesn't fit afororwhile. - Use labeled blocks for multi-level control flow instead of boolean flags or deeply nested conditionals.
- For linear searches, use an explicit optional result or return on a match.
- Label outer loops clearly when nested --
'search,'parse,'retryare better than'outer,'a. - Avoid
loopwithbreakwhen a simplerwhileorforexpresses the intent more clearly.