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
for i in 1..=10walks an inclusive range.whilerepeats until its condition is false.loopruns untilbreak, which can return a value.
Keywords and builtins used here
breakfnforifinletloopmainmutwhile
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.
Step 2 of 8 in Control flow, step 12 of 39 in Language basics.