Rust - Loop
Modern Looping in Rust
Section titled “Modern Looping in Rust”Looping is a fundamental concept in programming, allowing you to execute a block of code repeatedly. Rust provides three powerful and safe looping constructs to handle any iteration requirement: loop, while, and the idiomatic for.
The Infinite loop
Section titled “The Infinite loop”The loop keyword creates an infinite loop that will run forever until you explicitly tell it to stop using the break keyword. This is useful for scenarios like a server listening for connections or a program waiting for user input.
Example: A Simple Counter
Section titled “Example: A Simple Counter”fn main() { let mut counter = 0;
loop { counter += 1; println!("Counter is at: {}", counter);
if counter == 5 { break; // Exit the loop when counter reaches 5 } }}Pro Tip: A loop can also be used to return a value from the loop by placing the value after the break statement. This is great for retry logic.
fn main() { let mut counter = 0;
let result = loop { counter += 1; if counter == 10 { break counter * 2; // Exit and return 20 } };
println!("The result is {}", result); // Prints: The result is 20}Conditional Looping with while
Section titled “Conditional Looping with while”A while loop runs as long as a condition remains true. The condition is checked at the beginning of every iteration.
Example: A Countdown
Section titled “Example: A Countdown”fn main() { let mut number = 3;
while number != 0 { println!("{}!", number); number -= 1; }
println!("LIFTOFF!!!");}Output
Section titled “Output”3!2!1!LIFTOFF!!!While useful, while loops can sometimes be error-prone if the condition is not managed carefully. For iterating over a collection, Rust provides a safer and more concise alternative.
Idiomatic Iteration with for
Section titled “Idiomatic Iteration with for”The for loop is the most common and idiomatic loop in Rust. It is used to iterate over any type that implements the Iterator trait, such as arrays, vectors, or ranges. It’s safer and cleaner than a manual while loop because it handles the iteration logic for you, preventing common off-by-one errors.
Example: Iterating Over a Collection
Section titled “Example: Iterating Over a Collection”fn main() { let fruits = ["Apple", "Banana", "Cherry"];
for fruit in fruits.iter() { // .iter() borrows each element println!("I like {}s", fruit); }}Example: Iterating Over a Range
Section titled “Example: Iterating Over a Range”You can also iterate over a range of numbers. Note the use of 1..=3 for an inclusive range.
fn main() { // The range 1..4 is exclusive (1, 2, 3) // The range 1..=3 is inclusive (1, 2, 3) for number in 1..=3 { println!("{}", number); } println!("Ready!");}Controlling Loop Flow
Section titled “Controlling Loop Flow”As seen before, break exits the current loop immediately.
continue
Section titled “continue”The continue keyword skips the rest of the current iteration and proceeds to the next one. This is useful for filtering items within a loop.
Example: Skipping Even Numbers
Section titled “Example: Skipping Even Numbers”fn main() { for number in 0..10 { // Range from 0 to 9 if number % 2 == 0 { continue; // Skip the println! for even numbers } println!("Found an odd number: {}", number); }}Output
Section titled “Output”Found an odd number: 1Found an odd number: 3Found an odd number: 5Found an odd number: 7Found an odd number: 9