🎓 A1Learner
🔍

Rust For Loops

A for loop is a loop that visits each item in a group, one by one. No counting by hand is needed.

Counting by hand

A while loop can visit a list with a hand-kept counter. The counter is extra bookkeeping on every round:

fn main() {
    let fruits = ["apple", "pear", "plum"];
    let mut i = 0;
    while i < fruits.len() {
        println!("{}", fruits[i]);
        i += 1;
    }
}

Count with a range

0..5 visits 0, 1, 2, 3, 4 — the end is not included. Write 0..=5 when the end should be visited too:

for n in 0..5 {
    println!("{}", n);
}

Visit every item

for item in group visits each item in order — no counting by hand:

let fruits = ["apple", "pear", "plum"];
for fruit in fruits {
    println!("{}", fruit);
}

Borrow the list, keep the list

for item in &vec borrows each item, and the list stays yours afterwards. Without the &, the loop takes the items and the list is used up:

let fruits = ["apple", "pear"];
for fruit in &fruits {
    println!("{}", fruit);
}
println!("still {} fruits", fruits.len());

Change items as you visit

.iter() borrows items, .into_iter() takes them, and .iter_mut() borrows them so you can change them. Index numbers can change items too — here every score is multiplied by 10 through its index:

let mut scores = [1, 2, 3];
for i in 0..scores.len() {
    scores[i] *= 10;
}
println!("{:?}", scores);

Walk backwards with rev

.rev() turns a walk around:

for n in (1..=3).rev() {
    println!("{}", n);
}

Take bigger steps with step_by

step_by(3) visits every third item:

for n in (0..10).step_by(3) {
    println!("{}", n);
}

Example

fn main() {
    let fruits = ["apple", "pear", "plum"];
    for (i, fruit) in fruits.iter().enumerate() {
        println!("{}: {}", i + 1, fruit);
    }
    for n in (1..=3).rev() { print!("{} ", n); }
    println!("go!");
}

Key points

  • A backwards range like 5..1 is empty
  • A backwards range is not a countdown
  • The code compiles and the loop runs zero times
  • Use (1..=5).rev() to count down

In this example, fruits holds three words. The loop uses .iter().enumerate(), so each round gives a position and a borrowed fruit. i + 1 turns the positions 0, 1, 2 into the friendlier 1, 2, 3, and each line is printed. Next, (1..=3).rev() walks the numbers backwards: 3, 2, 1. print! keeps them on one line, and the final println! adds "go!" at the end.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

In for item in &vec, what do you get on each round?