Skip to content
Systems programming for what’s next.
— Vex

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 ​

vex
// 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 executed

for 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 ​

vex
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 ​

vex
'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 ​

vex
'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 ​

vex
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:

vex
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 elements

A 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 ​

vex
while condition {
    // body
}

// While-let pattern
while let Some(item) = queue.pop() {
    process(item)
}

loop -- Infinite Loop ​

vex
loop {
    // runs until break, return, or panic
    if done {
        break
    }
}

Loop Control Flow ​

ExpressionBehavior
breakExit the innermost loop immediately
break valueExit a value-producing loop with a value
break 'labelExit the named loop
break 'label valueYield from a value-producing loop or labelled block
continueSkip to next iteration of innermost loop
continue 'labelSkip 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.

vex
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:

vex
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 ​

vex
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 ​

  1. Use loop with break value for complex initialization or search logic that doesn't fit a for or while.
  2. Use labeled blocks for multi-level control flow instead of boolean flags or deeply nested conditionals.
  3. For linear searches, use an explicit optional result or return on a match.
  4. Label outer loops clearly when nested -- 'search, 'parse, 'retry are better than 'outer, 'a.
  5. Avoid loop with break when a simpler while or for expresses the intent more clearly.

Released under the MIT License.