typestar

Loops in Rust

Rust's three loop forms: for, while, and loop.

fn main() {
    let mut total = 0;
    for i in 1..=10 {
        total += i;
    }

    let mut count = 0;
    while count < 5 {
        count += 1;
    }

    let mut n = 0;
    let found = loop {
        n += 1;
        if n * n > 50 {
            break n;
        }
    };
    println!("{total} {count} {found}");
}

How it works

  1. for i in 1..=10 walks an inclusive range.
  2. while repeats until its condition is false.
  3. loop runs until break, which can return a value.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
226
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 2 of 8 in Control flow, step 12 of 39 in Language basics.

← Previous Next →

Loops in other languages