0Pricing
Learn Rust Coding · Lesson

Iterating Collections

for and iterators.

Looping with for

The for loop is the simplest way to visit each element in a collection.

fn main() {
    let nums = vec![1, 2, 3];
    for n in &nums {
        println!("{}", n);
    }
}

Looping Over Ranges

Ranges produce a sequence you can iterate. 1..5 is exclusive; 1..=5 includes the end.

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

All lessons in this course

  1. Vectors
  2. Strings and &str
  3. HashMaps
  4. Iterating Collections
← Back to Learn Rust Coding