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
break valuemakes theloopevaluate to that value.- A
'labellets an inner loop break the outer one. continue 'outerskips to the next outer iteration.
Keywords and builtins used here
breakfnforifinletloopmainmut
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.
Step 4 of 8 in Control flow, step 14 of 39 in Language basics.