Skip to content

Rust - Loop

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 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.

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
}

A while loop runs as long as a condition remains true. The condition is checked at the beginning of every iteration.

fn main() {
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
println!("LIFTOFF!!!");
}
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.

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.

fn main() {
let fruits = ["Apple", "Banana", "Cherry"];
for fruit in fruits.iter() { // .iter() borrows each element
println!("I like {}s", fruit);
}
}

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!");
}

As seen before, break exits the current loop immediately.

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.

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);
}
}
Found an odd number: 1
Found an odd number: 3
Found an odd number: 5
Found an odd number: 7
Found an odd number: 9