Rust Loops
Repeating code execution in Rust
π What are Loops in Rust?
Loops in Rust allow you to repeat code multiple times. Rust provides three types of loops: loop (infinite), while (conditional), and for (iterator-based) for different repetition needs.
// Simple loop example
let mut count = 0;
loop {
println!("Count: {}", count);
count += 1;
if count >= 3 {
break;
}
}
Output:
Count: 0
Count: 1
Count: 2
Count: 1
Count: 2
Types of Loops
loop
Infinite loop until break
loop {
// code here
if condition {
break;
}
}
while
Loop while condition is true
while condition {
// code here
}
for
Loop through collections
for item in collection {
// code here
}
Control
break and continue keywords
break; // exit loop
continue; // skip iteration
πΉ The loop Keyword
The loop keyword creates an infinite loop that runs until you break:
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 5 {
break counter * 2; // return value from loop
}
};
println!("Result: {}", result);
}
Output:
Result: 10
πΉ Loop Labels
Use labels to break from nested loops:
fn main() {
'outer: loop {
println!("Outer loop");
loop {
println!("Inner loop");
break 'outer; // breaks the outer loop
}
}
println!("Done!");
}
Output:
Outer loop
Inner loop
Done!
Inner loop
Done!
πΉ Using continue
Skip the current iteration and continue with the next:
fn main() {
for number in 1..=5 {
if number == 3 {
continue; // skip when number is 3
}
println!("Number: {}", number);
}
}
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Number: 2
Number: 4
Number: 5