Introduction
Rust provides three looping constructs: loop for an intentionally infinite loop, while for condition-based repetition, and for for iterating over a collection or range. Choosing the right one communicates intent clearly to readers of the code. A unique feature of loop is that it can return a value from the loop itself using break value;, which the other loop forms cannot do.
Cricket analogy: Rust's loop is like a bowler running unlimited trial deliveries until the coach calls break with a verdict value (the perfect line), while while repeats only as long as a fitness-test condition holds, and for strides through a fixed over count — each communicates intent clearly to teammates reading the drill plan.
Syntax
// infinite loop, can return a value
let result = loop {
// ...
break some_value;
};
// condition-based loop
while condition {
// ...
}
// iterator-based loop (idiomatic)
for item in iterable {
// ...
}
// labeled loops for nested control
'outer: loop {
loop {
break 'outer;
}
}Explanation
loop repeats a block forever until an explicit break, and break can carry a value out of the loop, making loop useful for retry logic or computations where the exit condition is discovered mid-iteration. while repeats as long as a bool condition holds, checked before each iteration. for is the idiomatic choice for iterating over ranges (like 0..5) or any type implementing IntoIterator, such as vectors and arrays — it avoids manual index bookkeeping and out-of-bounds errors. Labeled loops, written as 'label: loop { ... }, let you break or continue a specific outer loop from within nested loops using break 'label; or continue 'label;.
Cricket analogy: loop suits DRS retries, where break carries out the final decision value once discovered mid-review; while re-checks "run rate achievable" before every over; for is the idiomatic way to iterate 0..overs or a batting lineup without manual index tracking; and a labeled 'powerplay: loop lets you break 'powerplay from a nested fielding-position loop.
Example
fn main() {
// loop returning a value
let mut counter = 0;
let doubled = loop {
counter += 1;
if counter == 5 {
break counter * 2;
}
};
println!("doubled = {}", doubled);
// while loop
let mut n = 3;
while n != 0 {
println!("n = {}", n);
n -= 1;
}
// for loop over a range
for i in 0..3 {
println!("i = {}", i);
}
// labeled loops
'outer: for x in 0..3 {
for y in 0..3 {
if x == 1 && y == 1 {
break 'outer;
}
println!("x={}, y={}", x, y);
}
}
}Output
doubled = 10
n = 3
n = 2
n = 1
i = 0
i = 1
i = 2
x=0, y=0
x=0, y=1
x=0, y=2
x=1, y=0Key Takeaways
- loop repeats indefinitely until break, and can return a value via break value;.
- while repeats based on a bool condition checked before every iteration.
- for is the idiomatic way to iterate ranges and collections via IntoIterator.
- Labeled loops ('label:) let break and continue target a specific outer loop.
- Choosing loop vs while vs for communicates intent and often prevents index errors.
Practice what you learned
1. Which loop construct in Rust can directly return a value using break?
2. What is the idiomatic way to iterate over a vector's elements in Rust?
3. What does the label in `'outer: loop { ... break 'outer; }` do?
4. When is the condition of a while loop evaluated?
Was this page helpful?
You May Also Like
if-else Expressions in Rust
Learn how Rust's if-else works as an expression, requires bool conditions, and can return values directly.
match Expressions in Rust
Master Rust's exhaustive match expression for pattern matching on values, enums, tuples, and ranges.
if let and while let in Rust
Simplify single-pattern matching in Rust using the concise if let and while let constructs.
Vectors in Rust
A Vec<T> is a growable, heap-allocated list that lets you store a variable number of values of the same type.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics