typestar

while let in Rust

while let keeps looping as long as the pattern matches — draining a stack, say.

fn main() {
    let mut stack = vec![1, 2, 3, 4];
    while let Some(top) = stack.pop() {
        println!("popped {top}");
    }

    let mut chars = "abc".chars();
    while let Some(c) = chars.next() {
        print!("[{c}]");
    }
    println!();
}

How it works

  1. pop yields Some until the vector is empty.
  2. The loop ends when the pattern stops matching.
  3. It replaces a loop with a match and a break.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
209
Tokens
79
Three-star pace
85 tpm

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

Type this snippet

Step 5 of 8 in Control flow, step 15 of 39 in Language basics.

← Previous Next →