Rust — For Loops
Rust's for loop iterates — it doesn't count
let fruits = ["apple", "banana", "mango"];
for fruit in fruits {
println!("{}", fruit);
}
No index bookkeeping, no bounds checks at runtime — the compiler guarantees you can't fall off the end. This is why idiomatic Rust prefers for over while whenever a collection exists.
Ranges replace counting loops
for i in 0..5 { // 0 1 2 3 4 (end EXCLUSIVE)
print!("{} ", i);
}
for i in 0..=5 { // 0 1 2 3 4 5 (..= = inclusive)
print!("{} ", i);
}
for i in (1..10).step_by(2) { // 1 3 5 7 9
}
for i in (1..4).rev() { // 3 2 1 countdown
}
| Syntax | Produces |
|---|---|
0..5 | 0,1,2,3,4 |
0..=5 | 0..5 including 5 |
(1..10).step_by(2) | odd numbers |
(0..n).rev() | n-1 → 0 |
Looping collections
let scores = vec![90, 85, 77];
for s in &scores { // borrow: read each item
println!("{}", s);
}
for name in ["Ada", "Bo"] { … } // arrays too
let mut total = 0;
for s in &scores { total += s; }
The & matters — for s in scores would move the vector, making it unusable afterwards. Borrow with & to keep ownership (ownership lesson explains deeply).
enumerate — index + value together
for (i, fruit) in fruits.iter().enumerate() {
println!("{}. {}", i + 1, fruit);
}
// 1. apple · 2. banana · 3. mango
Never write for i in 0..list.len() just to index — enumerate is safer and expresses intent.
Nested loops
for row in 1..=3 {
for col in 1..=3 {
print!("{} ", row * col);
}
println!();
}
break/continue work here too
for n in 1..100 {
if n % 13 == 0 { break; }
if n % 2 == 0 { continue; }
print!("{} ", n);
}
Labels ('outer:) apply identically to nested for loops.
The index trap this design eliminates
Other languages:
for (let i = 0; i <= list.length; i++) … // 💥 off-by-one crash
Rust's iterator-based for makes that bug class unrepresentable — there is no manual bound to get wrong.
Rule: iterate collections with
for x in &coll; count with ranges; reservewhilefor condition-driven repetition.
Mini Practice
- FizzBuzz over 1..=30.
- Sum even numbers of a vector using
for … in &. - Print a 5×5 multiplication grid (nested).
- enumerate() a todo list starting at 1.
- Countdown from 10 with
.rev(); skip multiples of 3 via continue.
Next: functions →
Related Topics
Frequently Asked Questions about For Loops
What is For Loops in Rust?
For Loops is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn For Loops?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn For Loops.
Why is For Loops important in Rust?
For Loops is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.