Rust For
for loops through a range or a collection, one item at a time. Of the three loop types in Rust, this is the one you’ll reach for the most.
Looping over a range
Section titled “Looping over a range”fn main() { for i in 1..=5 { println!("{i}"); }}Output:
123451..=5 is a range that includes both ends (1 through 5). If you drop the = — 1..5 — it stops one short, giving you 1 through 4. That off-by-one is easy to trip over, so it’s worth double-checking which one you meant.
Looping over a collection
Section titled “Looping over a collection”This is where for really shines — looping over an array or vector without tracking an index yourself:
fn main() { let fruits = ["apple", "banana", "cherry"];
for fruit in fruits { println!("{fruit}"); }}Output:
applebananacherryCompare this to manually counting with a while loop and indexing (fruits[i]) — it’s shorter, and there’s no index to get wrong.
Getting the index too, with .enumerate()
Section titled “Getting the index too, with .enumerate()”If you need both the position and the value, use .enumerate():
fn main() { let fruits = ["apple", "banana", "cherry"];
for (index, fruit) in fruits.iter().enumerate() { println!("{index}: {fruit}"); }}Output:
0: apple1: banana2: cherryWhy for is preferred over while for counting
Section titled “Why for is preferred over while for counting”You could write a counting loop with while, but for with a range removes an entire category of mistakes — no manual counter to forget to update, and no risk of running one step past the end of an array. Rust programmers reach for for by default and only use while when there isn’t a natural range or collection to loop over.
for item in range_or_collection { ... }is the everyday loop in Rust.1..=5includes both ends;1..5stops one short of 5.- Loop directly over arrays/vectors to get each value without manual indexing.
- Use
.enumerate()when you need the index alongside the value.