Loops & Iterators
Rust supports loops to repeat code execution: standard for ranges, conditional while loops, and the infinite loop block.
1 Loop Expressions Returning values
In Rust, **`loop`** declares an infinite loop. It can also act as an expression, returning a value via the `break` keyword: `let value = loop { if condition { break 42; } };`.
2 Loops Code
Let's run a program illustrating while loops, range loops, and returning values from loops:
Rust — Loops
▶ Run Code
fn main() {
// 1. Loop expression returning value
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // Returns value from loop
}
};
println!("Result from loop: {}", result);
// 2. While loop
let mut num = 3;
print!("While loop countdown: ");
while num > 0 {
print!("{} ", num);
num -= 1;
}
println!();
// 3. For range loop (1..=3 includes 3)
print!("For range loop: ");
for x in 1..=3 {
print!("{} ", x);
}
println!();
}
3 Code Challenge
Challenge: Write a range loop that sums all odd numbers between 1 and 20. Skip the number 11 using the `continue` keyword, and print the computed sum at the end.