Concept Flow - Loop construct
Start
Execute loop body
Check condition or continue?
Repeat loop body
No
Exit loop
The loop runs the body repeatedly until a break condition stops it.
let mut count = 0; loop { if count == 3 { break; } count += 1; }
| Step | count | Condition (count == 3) | Action | Loop continues? |
|---|---|---|---|---|
| 1 | 0 | false | count += 1 -> 1 | Yes |
| 2 | 1 | false | count += 1 -> 2 | Yes |
| 3 | 2 | false | count += 1 -> 3 | Yes |
| 4 | 3 | true | break | No |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| count | 0 | 1 | 2 | 3 | 3 |
Rust loop construct syntax:
loop {
// code
if condition {
break;
}
}
The loop runs repeatedly until break is called.
Use break to stop the loop when a condition is met.loop keyword do in Rust?loop keywordloop keyword in Rust creates a loop that repeats forever unless stopped.loop, you must use break inside it; otherwise, it runs infinitely.break is called. -> Option Bloop = infinite loop until break [OK]loop runs forever unless broken [OK]loop runs a fixed number of timesloop with for or whileloop stops automaticallyloop to create an infinite loop.while True { println!("Hello"); } uses while True which is invalid syntax in Rust. for i in 0.. { println!("Hello"); } uses for with an infinite range, but 0.. is not valid without an end. repeat { println!("Hello"); } uses repeat which does not exist in Rust. loop { println!("Hello"); } correctly uses loop.loop [OK]loop keyword for infinite loops in Rust [OK]while True which is invalid in Rustrepeat which doesn't existfor without a proper rangelet mut count = 0;
loop {
count += 1;
if count == 3 {
break;
}
println!("{}", count);
}let mut i = 0;
loop {
if i == 5 {
break;
}
println!("{}", i);
}i is initialized but never changed inside the loop.i never increments, i == 5 is never true, so break is never reached, causing an infinite loop.loop to sum numbers from 1 to 5 in Rust?loop to add counter to sum.break to stop after 5break to exit loop.loop with a counter and break when counter > 5, adding each to sum. -> Option CPass the test and this pattern moves unknown