Loops
| loop forever | |
| while | |
| For over iterators | |
| break with value and continue |
loop forever
A loop block repeats until break stops it. It fits servers, retries, and any task with no fixed count:
let mut n = 0;
loop {
n += 1;
if n == 3 {
break;
}
}
while
A while loop checks its condition before each pass. It stops on its own once the condition turns false:
let mut n = 0;
while n < 3 {
n += 1;
}
For over iterators
A for loop walks an iterator and binds each item in turn. Ranges and vectors both work directly:
for i in 0..3 {
println!("{}", i);
}
break with value and continue
Break can carry a value out of a loop, while continue skips to the next pass. Together they shape flexible control flow:
let mut n = 0;
let v = loop {
n += 1;
if n == 2 {
continue;
}
if n == 4 {
break n;
}
};
Next: Ownership
Article author: Arthur Isaev