Course contentsShow
← Rust
Lesson 218 of 1,9103. Borrowing and ReferencesFree lesson

Iterators and Mutable Borrowing

Use mutable iterators to update collection elements while iterating.

Iterators and Mutable Borrowing

In this lesson, you will learn how to safely modify every element inside a collection while iterating over it using mutable references.

The Challenge of Mutation during Iteration

Up until now, you have used iterators primarily to read values. However, Rust’s ownership rules strictly enforce that you cannot have a mutable reference to a collection while simultaneously having immutable references to its items. When you want to update the elements of a vector, you need a way to obtain a mutable iterator.

Using iter_mut()

To change the contents of a collection, you use the .iter_mut() method instead of the standard .iter(). This method yields mutable references (&mut T) to each item in the collection, allowing you to modify them in place.

Because you are working with references, you must remember the dereferencing rules we discussed previously. To change the value behind a mutable reference, you use the dereference operator (*).

Consider this example where we increase every number in a vector by 1:

fn main() {
    let mut numbers = vec![1, 2, 3];

    // Request a mutable iterator
    for num in numbers.iter_mut() {
        // Dereference 'num' to update the actual value in the vector
        *num += 1;
    }

    println!("{:?}", numbers); // Output: [2, 3, 4]
}

Why This Works

When you call .iter_mut(), Rust ensures that only one mutable reference exists for each item at a time. By using the for loop, you gain temporary, exclusive access to each element. Once the loop body finishes for a specific element, that mutable reference is dropped, and the iterator moves to the next item. This prevents "aliasing" issues, where you might accidentally have two mutable pointers to the same data at the same time—a scenario Rust explicitly forbids.

By leveraging iter_mut(), you can transform your data efficiently without needing to clone or reallocate your collection.

Key Takeaway: Use .iter_mut() to obtain mutable references to collection elements, and use the * dereference operator to modify those values directly in place.