Loop Expressions
While Loops
A while loop repeatedly executes its body while a condition is true.
while_expr = "while" expression "{" block "}" ;
The condition expression MUST have type bool.
A while expression has type ().
The condition is evaluated before each iteration. If it is true, the body is executed and the condition is re-evaluated. If it is false, the loop terminates.
fn main() -> i32 {
let mut sum = 0;
let mut i = 1;
while i <= 10 {
sum = sum + i;
i = i + 1;
}
sum // 55
}
Infinite Loops
An infinite loop repeatedly executes its body unconditionally.
loop_expr = "loop" "{" block "}" ;
A loop expression has type ! (never), because it never produces a value. Even when break is present, the loop expression itself does not yield a result.
The only way to exit a loop is via break or return.
fn main() -> i32 {
let mut x = 0;
loop {
x = x + 1;
if x == 5 {
break;
}
}
x // 5
}
The loop expression is preferred over while true for infinite loops:
// Preferred
loop {
// ...
}
// Also valid, but less idiomatic
while true {
// ...
}
Break and Continue
The break expression exits the innermost enclosing loop.
The continue expression skips to the next iteration of the innermost enclosing loop.
Both break and continue MUST appear within a loop. Using them outside a loop is a compile-time error.
Both break and continue have the never type !.
Currently, break does not carry a value. A loop expression has type ! regardless of whether break is reachable, because the loop itself does not produce a value.
fn main() -> i32 {
let mut x = 0;
while true {
x = x + 1;
if x == 5 {
break;
}
}
x // 5
}
fn main() -> i32 {
let mut sum = 0;
let mut i = 0;
while i < 10 {
i = i + 1;
if i % 2 == 0 {
continue; // skip even numbers
}
sum = sum + i;
}
sum // 25 (1+3+5+7+9)
}
Nested Loops
In nested loops, break and continue affect only the innermost enclosing loop.
fn main() -> i32 {
let mut total = 0;
let mut outer = 0;
while outer < 3 {
let mut inner = 0;
while true {
inner = inner + 1;
total = total + 1;
if inner == 2 {
break; // exits inner loop only
}
}
outer = outer + 1;
}
total // 6
}