For Loop

A for expression extracts values from an iterator until the iterator is empty. for loops in Rust use a similar syntax to Python with the in keyword.

rust
// Example for loop.
for i in vec!["stuff", "things"] {
    print!("{} ", i);
} // => stuff things

// Mark a loop level with a tag: {'outer} to use as a break reference point.
'outer: for i in vec!["stuff", "things", "blah"] {
    for j in vec!["bleh", "blah", "blow"] {
        if i == j {
            println!("i: {} j: {}", i, j);
            break 'outer; // Breaks out of the loop at the {'outer} tag.
        }
    }
} // => i: blah j: blah

For Loop Considerations

  • For loops can iterate over anything that implements the IntoIterator trait.
  • Tags can be used to break out of a nested for loop at different reference points.
  • Tags are prefixed with a single (') quote.

While Loop

A while expression executes the loop body as long as some conditional expression evaluates to true.

rust
// Example while loop.
let mut tick = 3;

while tick >= 0 { // conditional expression => `tick >= 0`
    if tick == 0 {
        print!("BOOM!");
    } else {
        print!("{} ", tick);
    }
    tick -= 1;
} // => 3 2 1 BOOM!

While Loop Considerations

  • A while loop cannot break with a value and always evaluates to ().

Loop

A loop expression executes an unconditional infinite loop.

rust
// Example unconditional loop.
loop {
    println!("💵 make it rain 💵");
} // => All the moneys

Loop Considerations

  • A break statement is required to exit out of a loop expression.

Tags

rust