Loops
Prerequisites: Conditionals
Rust has three loop keywords: loop, while, and for.
Syntax
loop {
// repeats forever until `break`
}
while condition {
// repeats while condition is true
}
for item in collection {
// runs once per item
}
looprepeats until youbreak. Becauseloopis an expression,break valuemakes the loop produce that value.whilechecks a condition before each pass.forgoes through each item of something iterable: a range, an array, or (later) a vector. It's the loop you'll use most.- Ranges —
1..4is 1, 2, 3 (the end is excluded);1..=4includes the end.(1..=3).rev()counts backwards. continueskips to the next pass;breakexits the loop.- Labels such as
'outer:letbreakorcontinuetarget an outer loop when loops are nested. .iter().enumerate()gives you each item together with its index, as a pair(index, item).
Example
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 5 {
break counter * 10;
}
};
println!("loop result: {result}");
let mut n = 3;
while n > 0 {
println!("{n}...");
n -= 1;
}
println!("Liftoff!");
for i in 1..4 {
print!("[{i}]");
}
println!();
for i in (1..=3).rev() {
print!("[{i}]");
}
println!();
let fruits = ["apple", "banana", "cherry"];
for fruit in fruits {
println!("{fruit}");
}
for (index, fruit) in fruits.iter().enumerate() {
println!("{index}: {fruit}");
}
for i in 1..=6 {
if i % 2 == 0 {
continue;
}
print!("[{i}]");
}
println!();
'outer: for x in 1..=3 {
for y in 1..=3 {
if x * y == 4 {
break 'outer;
}
println!("{x} x {y} = {}", x * y);
}
}
}
Expected output
loop result: 50
3...
2...
1...
Liftoff!
[1][2][3]
[3][2][1]
apple
banana
cherry
0: apple
1: banana
2: cherry
[1][3][5]
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
print! doesn't add a newline, so the bracketed numbers share a line
until the println!() that follows each loop.
Common mistakes
- Returning a value from
while. Onlyloopcanbreakwith a value:
error[E0571]: `break` with value from a `while` loop
- Forgetting
muton a loop counter:
let n = 3;
while n > 0 {
n -= 1;
}
error[E0384]: cannot assign twice to immutable variable `n`
- Off-by-one errors with ranges:
1..10stops at9. Use1..=10to include10. - Looping over indexes (
for i in 0..fruits.len()) and then writingfruits[i]. It works, butfor fruit in fruits(or.enumerate()if you need the index) is clearer and can't go out of bounds.
Practice
Use a for loop over the range 1 to 10 (inclusive) to add up only the
even numbers, then print Sum of even numbers: 30.
Show solution
fn main() {
let mut sum = 0;
for n in 1..=10 {
if n % 2 == 0 {
sum += n;
}
}
println!("Sum of even numbers: {sum}");
}