Loops and ranges
loop, while and for — and the half-open range that stops one short.
- Choose between loop, while and for
- Iterate over arrays with iter() and over ranges
- Read half-open and inclusive ranges correctly
Rust has three loops, and loops/src/main.rs uses each one.
let mut id = 0;
loop {
if id == 10 { break; }
id += 1;
} // id is 10
while id != 0 {
id -= 1;
} // id is 0
let array = [1, 2, 3, 4, 5];
for element in array.iter() { println!("Element from array: {}", element); }
for number in 1..6 { println!("Number from range: {}", number) }
-
loopruns forever until abreak. It is also an expression:break valuemakes the loop producevalue, which is handy for retry loops —let n = loop { ... break attempts; };. -
whilechecks its condition before every pass, and is the right choice when the number of passes is not known in advance. -
forwalks over anything iterable, and is the loop to reach for first: it cannot run past the end of a collection, and needs no index variable.
Ranges
1..6 is a half-open range: it starts at 1 and stops before 6, so the last loop prints 1 to 5. For an inclusive range, write 1..=6. The half-open form matches how indices work — 0..array.len() visits every valid index exactly once — and (1..6).rev() counts down.
Iterating over an array
array.iter() yields a reference to each element in turn, leaving the array untouched. Since Rust 1.53, for element in array also works and yields the elements by value. For both index and value, for (i, element) in array.iter().enumerate() mirrors Python’s enumerate.
Try it yourself. Rewrite the first loop so that the loop itself produces the final count with break: let id = loop { ... break counter; };. Then sum the array with array.iter().sum::<i32>(), and print the squares of 1 to 6 inclusive with a single range and map.