← Back to Rust Course | Chapter 9: Collections | Lesson 5 of 6

Iterating Collections

Iterating means visiting each item in a list, one after another, to look at or use it.

Iterating by Reference with iter

.iter() produces an iterator of references to each element, leaving the original collection untouched and still usable afterward.

Example: Iterating by Reference with iter

markup
fn main() {
    let numbers = vec![1, 2, 3];
    for n in numbers.iter() {
        println!("Value: {}", n);
    }
    println!("Still usable: {:?}", numbers);
}

Mutating in Place with iter_mut

.iter_mut() produces mutable references to each element, allowing you to modify the collection's contents directly during iteration.

Example: Mutating in Place with iter_mut

markup
fn main() {
    let mut numbers = vec![1, 2, 3];
    for n in numbers.iter_mut() {
        *n *= 10;
    }
    println!("{:?}", numbers);
}

Taking Ownership with into_iter

Iterating a collection by value (with into_iter(), or a plain for x in collection) consumes the collection, moving each element out one at a time.

Example: Taking Ownership with into_iter

markup
fn main() {
    let words = vec![String::from("a"), String::from("b")];
    for word in words.into_iter() {
        println!("Owned word: {}", word);
    }
}

Chaining Iterator Adapters

Iterator methods like .map() and .filter() can be chained together to transform and select elements declaratively before finally collecting or summing the results.

Example: Chaining Iterator Adapters

markup
fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let sum_of_squares: i32 = numbers.iter().map(|n| n * n).filter(|n| n % 2 == 0).sum();
    println!("Sum of even squares: {}", sum_of_squares);
}
Common Mistakes
  1. Using for item in collection (taking ownership) when you only meant to read the items, needing .iter() instead.
  2. Forgetting .iter_mut() exists for modifying every element of a collection in place during iteration.
  3. Assuming .iter() on a Vec<T> yields T values directly, when it actually yields &T references.
Chapter Summary
  • .iter() yields immutable references to each element without taking ownership of the collection.
  • .iter_mut() yields mutable references, letting you modify elements in place during iteration.
  • into_iter() (or a bare for x in collection) takes ownership of the collection and its elements.
  • Iterator adapters like .map(), .filter(), and .sum() can be chained together to process collections declaratively.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.