Rust For Loop
Iterating through collections in Rust
🔁 What is a For Loop?
For loops in Rust iterate through collections like arrays, vectors, and ranges. They're the safest and most common way to repeat code a specific number of times or process each item in a collection.
// Basic for loop with range
for number in 1..=5 {
println!("Number: {}", number);
}
// For loop with array
let fruits = ["apple", "banana", "orange"];
for fruit in fruits {
println!("Fruit: {}", fruit);
}
Output:
Number: 2
Number: 3
Number: 4
Number: 5
Fruit: apple
Fruit: banana
Fruit: orange
For Loop Types
Ranges
Loop through number ranges
for i in 0..5 {
// 0, 1, 2, 3, 4
}
for i in 1..=5 {
// 1, 2, 3, 4, 5
}
Arrays
Iterate through array elements
let arr = [1, 2, 3];
for item in arr {
println!("{}", item);
}
Vectors
Loop through vector items
let vec = vec![1, 2, 3];
for item in &vec {
println!("{}", item);
}
Enumerate
Get index and value together
for (i, item) in arr.iter().enumerate() {
println!("{}: {}", i, item);
}
🔹 For Loop with Ranges
Ranges are the most common way to repeat code a specific number of times:
fn main() {
// Exclusive range (doesn't include 5)
println!("Counting 0 to 4:");
for i in 0..5 {
println!("{}", i);
}
// Inclusive range (includes 5)
println!("\nCountdown 5 to 1:");
for i in (1..=5).rev() {
println!("{}", i);
}
println!("Blast off! 🚀");
}
Output:
0
1
2
3
4
Countdown 5 to 1:
5
4
3
2
1
Blast off! 🚀
🔹 For Loop with Arrays
Iterate through array elements directly:
fn main() {
let colors = ["red", "green", "blue", "yellow"];
// Direct iteration
println!("Colors:");
for color in colors {
println!("- {}", color);
}
// With index using enumerate
println!("\nColors with index:");
for (index, color) in colors.iter().enumerate() {
println!("{}: {}", index + 1, color);
}
}
Output:
- red
- green
- blue
- yellow
Colors with index:
1: red
2: green
3: blue
4: yellow
🔹 For Loop with Vectors
Working with vectors (dynamic arrays):
fn main() {
let mut scores = vec![85, 92, 78, 96, 88];
// Read-only iteration
println!("Original scores:");
for score in &scores {
println!("Score: {}", score);
}
// Modify elements
for score in &mut scores {
*score += 5; // Add 5 bonus points
}
println!("\nAfter bonus:");
for (i, score) in scores.iter().enumerate() {
println!("Student {}: {}", i + 1, score);
}
}
Output:
Score: 85
Score: 92
Score: 78
Score: 96
Score: 88
After bonus:
Student 1: 90
Student 2: 97
Student 3: 83
Student 4: 101
Student 5: 93
🔹 Nested For Loops
Use nested loops for multi-dimensional data:
fn main() {
// Multiplication table
println!("Multiplication Table (1-5):");
for i in 1..=5 {
for j in 1..=5 {
print!("{:3} ", i * j);
}
println!(); // New line after each row
}
}
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25