typestar

Loops that return values in Rust

loop is an expression: break carries a value out, and labels pick which loop to leave.

fn main() {
    let mut n = 1;
    let doubled = loop {
        n *= 2;
        if n > 50 {
            break n;
        }
    };
    println!("first over fifty: {doubled}");

    'outer: for a in 1..10 {
        for b in 1..10 {
            if a * b == 12 {
                println!("{a} x {b}");
                break 'outer;
            }
        }
    }
}

How it works

  1. break value makes the loop evaluate to that value.
  2. A 'label lets an inner loop break the outer one.
  3. continue 'outer skips to the next outer iteration.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
227
Tokens
78
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 4 of 8 in Control flow, step 14 of 39 in Language basics.

← Previous Next →