Rust Tutorial: Loops in Rust
Use loop, while, and for to repeat code and iterate in Rust.
Concepts in this chapter
You will learn and practice:
- **loop** — infinite loop; break to exit
- **while** — condition before each iteration
- **for** — iterate over a range or iterator (e.g. 1..=5, collection.iter())
- **break and continue** — exit loop or skip to next iteration
- **Range** — 1..5 (exclusive end), 1..=5 (inclusive)
---
loop and break
```rust
let mut n = 3;
loop {
println!("{}", n);
n -= 1;
if n == 0 {
break;
}
}
println!("Liftoff!");
```
---
while
```rust
let mut n = 3;
while n > 0 {
println!("{}", n);
n -= 1;
}
```
---
for over a range
```rust
for i in 1..=5 {
println!("{}", i);
}
```
---
What's Next?
Next: **Arrays and Slices** — fixed-size arrays and dynamic slices.
What you'll learn in this Rust loops in rust tutorial
This interactive Rust tutorial has 5 hands-on exercises. Estimated time: 12 minutes.
- for over Range — Use a for loop over the range 1..=5 to print the numbers 1 through 5, each on its own line.
- while Loop — Use a while loop to count down from 3 to 1, printing each number, then print "Liftoff!" after the loop.
- for over Slice — Loop over the array `let fruits = ["apple", "banana", "cherry"]` and print each fruit on its own line.
- break and continue — Loop from 1 to 6. Use continue to skip even numbers and break if the number exceeds 5. Print only 1, 3, and 5.
- Sum in a Loop — Use a for loop over 1..=10 to compute the sum and print the result.
Rust Loops in Rust concepts covered
- Concepts in this chapter
- loop and break
- while
- for over a range
- What's Next?