Rust Loops
Loops repeat actions, like counting or checking items. Rust has three types of loops, but `for loop` is the one you'll use most often.
The same line, written five times
Printing five numbers without a loop repeats the same line five times:
fn main() {
println!("{}", 1);
println!("{}", 2);
println!("{}", 3);
println!("{}", 4);
println!("{}", 5);
}for visits each number in a range
0..3 gives the numbers 0, 1, 2 — the end number is left out:
for n in 0..3 { println!("{}", n); }Write ..= to include the end
One extra sign changes the end rule: .. stops before the end, ..= runs up to it and includes it:
for n in 1..=3 {
println!("{}", n);
}A range is a value of its own
A range is not only loop spelling. You can save one in a variable and ask questions about it:
let range = 1..=5;
println!("has 3 = {}", range.contains(&3));
println!("has 9 = {}", range.contains(&9));
let backwards = 5..1;
println!("backwards is empty = {}", backwards.is_empty());loop repeats until break
loop on its own would repeat forever. A break inside is the way out:
let mut n = 0;
loop {
n += 1;
if n == 3 { break; }
}
println!("n = {}", n);Example
fn main() {
let mut sum = 0;
for n in 1..=5 { sum += n; }
println!("sum 1..=5 = {}", sum);
let mut doubled = [0; 3];
for n in 1..=3 { doubled[(n - 1) as usize] = n * 2; }
println!("{:?}", doubled);
}Key points
- The three are loop, while, and for.
- Each loop fits a different job.
In this example, the for loop runs once for each number from 1 to 5. Each number is added to sum, so sum ends at 15. The println! prints that total. A second loop then fills an array. It doubles each number from 1 to 3 and stores it in the next free slot. The second println! shows [2, 4, 6].
Note
Unlike C-style loops, a Rust for loop has no manual counter to get wrong.
It cannot run past the end of a list.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
If you print x for each x in 0..3, what do you get?