`loop` / `while` / `for`
Rust has loop, while, while let, and for. for walks an iterator. There is no C-style three-clause for and no foreach keyword.
Detailed Explanation
loop { ... } runs forever until you break. It is the primitive. Everything else is sugar or a condition on top. Because loop is an expression, break value makes the whole loop evaluate to value, which is how you write "keep trying until it works, then hand the result out".
while condition { ... } is loop with a test at the top. Use it when the stop condition is a boolean you already have: a flag, a counter, a done bit from a parser. while let pattern = expr is the same idea for a pattern: keep going while expr matches. The classic use is while let Some(item) = rx.recv() or while let Some(line) = lines.next().
for item in collection is the loop you write most often. It desugars to IntoIterator: the collection is converted into an iterator, and the loop calls next until it gets None. for i in 0..n iterates a range. for item in &vec iterates by shared reference and leaves vec usable. for item in &mut vec iterates by mutable reference. for item in vec moves the elements out and consumes the vector.
There is no for (int i = 0; i < n; i++). A range, an iterator adapter, or an explicit loop with a counter replaces it. That is a style choice with teeth: indexing a Vec on every iteration re-checks bounds, while for item in &vec does not. Prefer iterating values over iterating indexes unless you need the index, in which case .iter().enumerate() gives you both.
Labels let you talk to an outer loop. 'outer: for row in rows { for cell in row { if cell.empty() { continue 'outer; } } }. Without the label, continue would skip the rest of the inner row only.
What it costs: a for over a slice is as cheap as a pointer walk after optimisation. A for over .filter().map() is usually fused into one pass. The cost you should notice is accidental clones inside the body and accidental for i in 0..vec.len() { vec[i] } when &vec would do.
When you reach for loop: retry, servers, or a break value. When you reach for while: a boolean condition. When you reach for for: anything that implements IntoIterator, which is almost every collection.
Code Examples
fn main() {
let mut n = 1;
let found = loop {
n *= 2;
if n > 10 {
break n;
}
};
println!("{found}"); // prints: 16
let names = ["ada", "grace", "alan"];
for (i, name) in names.iter().enumerate() {
println!("{i}:{name}");
}
// prints:
// 0:ada
// 1:grace
// 2:alan
}Common Gotchas
`for x in vec` consumes the vector
After the loop, `vec` is moved. Iterate `&vec` or `vec.iter()` when you still need the collection.
Ranges exclude the end by default
`0..3` yields 0, 1, 2. `0..=3` includes 3. Off-by-one bugs hide in the `..` versus `..=` choice.
Index loops re-check bounds
`for i in 0..v.len() { use(v[i]) }` panics if you mutate the length, and it is slower than `for x in &v`.
`break` values need `loop`
You cannot `break x` from `for` or `while`. Rebuild with `loop` or use a helper function that `return`s.