Skip to content

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.

fn main() {
for i in 1..=5 {
println!("{i}");
}
}

Output:

1
2
3
4
5
▶ Try it Yourself

1..=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.

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:

apple
banana
cherry
▶ Try it Yourself

Compare this to manually counting with a while loop and indexing (fruits[i]) — it’s shorter, and there’s no index to get wrong.

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: apple
1: banana
2: cherry
▶ Try it Yourself

Why 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..=5 includes both ends; 1..5 stops 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.