Skip to main content

Loop

Iteration using loop:

src/05-loop/main.rs
fn main() {
// loop and break
let mut count = 5;
loop {
println!("{count}");
count -= 1;

if count < 0 {
println!("Blast off.");
break;
}
}
}

While loop

src/05-while-loop/main.rs
use std::thread::sleep;
use std::time::Duration;

fn main() {
let mut count = 5;
let time = Duration::from_secs(1);

while count > 0 {
println!("{count}");
sleep(time);
count -= 1;
}

println!("LIFTOFF!!!");
}

For loop

src/05-for-loop/main.rs
fn main() {
for number in (0..6).rev() {
// (0..6) is same as (0..=5)
// increment by step (2..=10).step_by(2)
println!("{number}");
}
println!("LIFTOFF!!!");
}

List enumeration

src/05-list-enum/main.rs
fn main() {
let list = ["apple", "banana", "orange"];

for item in list {
println!("{item}");
}
}