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.