- Loops - The infinite Loop The loop keyword create an infinite loop.You must explicitly use break to exit.
fn main() {
let mut counter = 0;
loop{
counter += 1;
println!("Counter = {}", counter);
if counter == 3{
break; // exits the loop
}
}
}
OUTPUT
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Counter = 5
- While - Loop while a Condition is True
- a while loop continues as long as a condition is true
fn main() {
let mut number = 3;
while number > 0 {
println!("{}!", number);
number -= 1;
}
println!("LIFTOFF 🚀")
}
OUTPUT
3!
2!
1!
LIFTOFF 🚀
- for - Looping Through Ranges and Collections
- The for loop is the most idiomatic in Rust
fn main() {
for i in 1..5 {
println!("i = {}", i);
}
}
Output
i = 1
i = 2
i = 3
i = 4
Top comments (0)