for Loops and Ranges
for loop lets you walk through a list of numbers or items one by one, automatically, without any bookkeeping.In this page:
Iterating a Range
A range like 0..5 produces the sequence 0, 1, 2, 3, 4 -- note the upper bound is exclusive. A for loop can iterate directly over such a range without any manual counter.
Example: Iterating a Range
fn main() {
for i in 0..5 {
println!("i = {}", i);
}
}
Login to try C/C++/Java/PHP code in the editor
Inclusive Ranges
Adding an equals sign, 0..=5, creates an inclusive range that includes the final number, producing 0 through 5. Use this when you want the endpoint included.
Example: Inclusive Ranges
fn main() {
for i in 1..=3 {
println!("Count: {}", i);
}
}
Login to try C/C++/Java/PHP code in the editor
Iterating a Collection
for loops can iterate directly over the elements of an array or other collection, giving you each value in turn without ever touching an index.
Example: Iterating a Collection
fn main() {
let fruits = ["apple", "banana", "cherry"];
for fruit in fruits.iter() {
println!("Fruit: {}", fruit);
}
}
Login to try C/C++/Java/PHP code in the editor
Using enumerate for Index and Value
When you need both the position and the value while iterating, .enumerate() wraps an iterator to yield (index, value) pairs, avoiding manual counters entirely.
Example: Using enumerate for Index and Value
fn main() {
let colors = ["red", "green", "blue"];
for (index, color) in colors.iter().enumerate() {
println!("{}: {}", index, color);
}
}
Login to try C/C++/Java/PHP code in the editor
- Writing
for i in 0..nwhen you actually need to includen, forgetting that..is exclusive of the upper bound. - Manually managing an index variable and a
whileloop instead of using Rust's safer and more idiomaticforloop. - Trying to modify a collection's length while iterating over it directly by value, which the borrow checker will reject.
for item in collectioniterates over every element of a collection or range automatically.0..5is an exclusive range (0 to 4);0..=5is inclusive (0 to 5).forloops are preferred over manual indexing because they eliminate off-by-one errors..enumerate()can be combined withforto get both the index and the value.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: