Rust Loops Tutorial | loop while for for Beginners (2024)
Video: Rust Loops Tutorial | loop while for for Beginners (2024) by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Loops Tutorial: loop, while, and for Explained
This tutorial covers the three primary loop types in Rust: the infinite loop with break, the conditional while loop, and the range-based for loop. You'll learn how to use each loop effectively with clear examples and explanations.
Code
fn main() {
// Example 1: Infinite loop with break
let mut count = 0;
loop {
count = count + 1; // Increment count
println!("Count is: {}", count);
if count == 5 {
break; // Exit loop when count reaches 5
}
}
// Example 2: While loop countdown
let mut seconds = 5;
while seconds > 0 { // Continue while seconds is greater than 0
println!("{} seconds remaining...", seconds);
seconds = seconds - 1; // Decrement seconds
}
println!("Liftoff!");
// Example 3: For loop with range
for number in 1..6 { // Range 1 to 5 (6 is excluded)
println!("Number: {}", number);
}
// Use 1..=5 for an inclusive range that includes 5
}
Key Points
loopcreates an infinite loop that must be exited withbreak.whileloops continue as long as a condition remains true.forloops iterate cleanly over ranges or collections.- Ranges like
1..6exclude the end value, while1..=5includes it. - Declare variables as
mutwhen you need to modify them inside loops.