Rust For Loop
The for loop is the loop Rust programmers reach for first. Instead of managing a counter yourself, you tell for what to go through, and it hands you one item at a time. It is shorter to write, easier to read, and it can never accidentally run past the end.
Looping over a range
A range is a sequence of numbers. 1..5 means 1, 2, 3, 4: it stops before 5. If you want to include the last number, write 1..=5.
fn main() {
for i in 1..=5 {
println!("{} x 3 = {}", i, i * 3);
}
}1 x 3 = 3 2 x 3 = 6 3 x 3 = 9 4 x 3 = 12 5 x 3 = 15
The variable i is created fresh for each round and holds the current number. You can call it anything you like, but i is the traditional name for a counter.
Backwards and in steps
Add .rev() to go backwards, and .step_by(n) to jump by more than one. Notice the round brackets around the range when you add these:
fn main() {
for n in (1..=5).rev() {
print!("{} ", n);
}
println!("Go!");
for even in (0..=10).step_by(2) {
print!("{} ", even);
}
println!();
}5 4 3 2 1 Go! 0 2 4 6 8 10
Looping over a list
for can walk through a list of values just as easily. Here is an array of names. We will learn about arrays properly later; for now, enjoy how simple the loop is:
fn main() {
let friends = ["Asha", "Ravi", "Leela"];
for name in friends {
println!("Hello, {}!", name);
}
for (position, name) in friends.iter().enumerate() {
println!("{}. {}", position + 1, name);
}
}Hello, Asha! Hello, Ravi! Hello, Leela! 1. Asha 2. Ravi 3. Leela
enumerate gives you each item together with its position. Positions start at 0, which is why we print position + 1 for people, who like to count from 1.
Adding things up
A very common pattern is to keep a running total while you loop:
fn main() {
let mut total = 0;
for n in 1..=100 {
total += n;
}
println!("1 + 2 + ... + 100 = {}", total);
}1 + 2 + ... + 100 = 5050
Practice exercises
- Print the multiplication table of 7 from 7 x 1 to 7 x 10.
- Add up all the odd numbers from 1 to 99.
- Make an array of five fruits and print them numbered from 1 to 5.