Loops: loop, while, for
Rust provides three primary looping constructs: loop
, while
, and for
.
loop
Executes a block endlessly until manually broken.
loop {
println!("This will repeat forever");
break;
}
Use break
to exit the loop and continue
to skip to the next iteration.
while
Repeats as long as the condition is true
.
let mut number = 3;
while number != 0 {
println!("{}", number);
number -= 1;
}
for
Used for iterating over a range or collection.
for number in 1..4 {
println!("{}", number);
}
1..4
is a range that includes 1, 2, 3.