0Pricing
Learn Rust Coding · Lesson

Iterating Collections

for and iterators.

Iterating Collections is a free Learn Rust Coding lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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);
    }
}

The iter Method

Calling .iter() creates an iterator that yields references to each element. Iterators are lazy until consumed.

fn main() {
    let v = vec![10, 20, 30];
    let mut it = v.iter();
    println!("{:?}", it.next());
    println!("{:?}", it.next());
}

Three Ways to Iterate

Vectors offer three iteration styles:

  • iter() — yields &T (borrow).
  • iter_mut() — yields &mut T (mutable borrow).
  • into_iter() — yields T (takes ownership).
fn main() {
    let v = vec![1, 2, 3];
    for x in v.into_iter() {
        println!("owned {}", x);
    }
}

Transforming with map

map applies a closure to each element, producing a new iterator. Use collect to gather results.

fn main() {
    let v = vec![1, 2, 3];
    let squared: Vec<i32> = v.iter().map(|x| x * x).collect();
    println!("{:?}", squared);
}

Selecting with filter

filter keeps only elements for which the closure returns true.

fn main() {
    let v = vec![1, 2, 3, 4, 5];
    let odds: Vec<i32> = v.into_iter().filter(|x| x % 2 == 1).collect();
    println!("{:?}", odds);
}

Aggregating with sum and count

Consuming methods reduce an iterator to a single value, such as sum, count, max, and min.

fn main() {
    let v = vec![4, 8, 15, 16];
    let total: i32 = v.iter().sum();
    let how_many = v.iter().count();
    println!("sum {} count {}", total, how_many);
}

Chaining Adapters

Iterator methods can be chained into a clear pipeline. Each step transforms the stream before the final consumer.

fn main() {
    let v = vec![1, 2, 3, 4, 5, 6];
    let result: i32 = v.iter()
        .filter(|x| *x % 2 == 0)
        .map(|x| x * 10)
        .sum();
    println!("{}", result);
}

enumerate for Indices

enumerate pairs each element with its index, yielding tuples (index, value).

fn main() {
    let letters = vec!['a', 'b', 'c'];
    for (i, ch) in letters.iter().enumerate() {
        println!("{}: {}", i, ch);
    }
}

Iterating a HashMap

Iterators work on maps too. Looping yields key-value tuples.

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();
    m.insert("a", 1);
    m.insert("b", 2);
    for (k, v) in &m {
        println!("{} -> {}", k, v);
    }
}

for vs Iterator Methods

A plain for loop is great for side effects like printing. Iterator adapters (map, filter, sum) shine when transforming data into a new value.

fn main() {
    let v = vec![2, 4, 6];
    let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
    for x in &doubled {
        println!("{}", x);
    }
}

Quick Check

Recall the role of iterator adapters.

Recap

Iterating collections in Rust:

  • for x in &collection for simple loops.
  • iter, iter_mut, into_iter control borrowing.
  • Adapters: map, filter, enumerate.
  • Consumers: collect, sum, count, max.
fn main() {
    let prices = vec![10, 25, 40];
    let with_tax: Vec<i32> = prices.iter().map(|p| p + p / 5).collect();
    let total: i32 = with_tax.iter().sum();
    println!("{:?} total {}", with_tax, total);
}

Frequently asked questions

Is the “Iterating Collections” lesson free?

Yes — the full text of “Iterating Collections” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.

What will I learn in “Iterating Collections”?

for and iterators. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn Rust Coding?

No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Iterating Collections” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn Rust Coding lesson?

Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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