...
Code Block |
---|
fn main() { let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; println!("The result is {result}"); } |
While
...
Code Block |
---|
fn main() { let mut number = 3; while number != 0 { println!("{number}!"); number -= 1; } println!("LIFTOFF!!!"); } |
For
Looping Through a Collection with for
Code Block |
---|
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
} |
Here’s what the countdown would look like using a for loop and another method we’ve not yet talked about, rev, to reverse the range:
Code Block |
---|
fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
} |
...