Repeat with an exit plan.
Choose the loop that makes termination and iteration clearest.
01 Understand the contract
Use for to iterate over a range or collection, while for a condition checked before each iteration, and loop when the exit is controlled inside the body. break exits and continue skips to the next iteration. A loop expression can return a value with break value. Ranges such as 0..3 exclude the end, while 0..=3 include it. A simple termination argument is useful even in everyday code: explain what changes on every iteration and why an exit must eventually happen.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let sum: i32 = (1..=4).sum();
let mut n = 0;
let found = loop {
n += 1;
if n * n >= 20 {
break n;
}
};
println!("sum={sum}, first square boundary={found}");
}sum=10, first square boundary=5
- 1
The inclusive range contributes 1, 2, 3, and 4.
- 2
n increases each iteration until its square reaches the threshold.
- 3
break n gives the loop its result.
cargo run -p lesson_loops03 Mind the boundary
04 Your next build
Use a for loop to collect multiples of three from 1 through 10.
Reveal one possible solution +
fn main() {
let mut values = Vec::new();
for n in 1..=10 {
if n % 3 == 0 {
values.push(n);
}
}
assert_eq!(values, [3, 6, 9]);
}05 Check your reasoning
Which values are in 1..4?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.