liveBook · Manning

Iter_mut

As explained in Idiomatic Rust

iter_mut is a collection method that returns an iterator over mutable references to the collection's elements without consuming the collection.

Use `iter_mut()` when you need to visit a collection’s elements through mutable references without consuming the collection. It takes `&mut self` and returns a separate iterator; `iter()` uses `&self` for immutable references, while `into_iter(self)` consumes the collection. section 3.2.4

impl<T> LinkedList<T> {
    fn iter(&self) -> Iter<T> {
        Iter {
            next: Some(self.head.clone()),
            data: None,
            phantom: PhantomData,
        }
    }
    fn iter_mut(&mut self) -> IterMut<T> {
        IterMut {
            next: Some(self.head.clone()),
            data: None,
            phantom: PhantomData,
        }
    }
}

The linked-list method constructs an `IterMut` from the list head. The iterator, rather than the list, holds traversal state. section 3.2.4

The completed `IterMut` implements `Iterator` with `Item = &'a mut T`. Its `next()` uses an unsafe pointer dereference to produce that reference. Treat this as an implementation detail requiring care, not a reason to use unsafe code when calling `iter_mut()`. section 3.2.4

Calling iter_mut

A linked-list example calls `dinosaurs.iter_mut().for_each(|data| println!("data={}", data));`. It demonstrates traversal, but prints each item rather than modifying it. An `IntoIterator` implementation for `&mut LinkedList<T>` also delegates to `iter_mut()`. section 3.2.4

How Idiomatic Rust covers it

How deep it goes
Works through a linked-list iterator constructor and `next()` implementation, including its unsafe pointer dereference.
Examples
Shows `iter_mut().for_each()` printing linked-list elements; the example does not modify them.
What it assumes
Assumes familiarity with Rust references, traits, and generic types; briefly illustrates lifetime syntax while developing the iterators.
What you can do after
Apply it via `iter_mut()` to traverse a collection without consuming it, or implement a separate mutable iterator for a linked list.
How it connects
Relates mutable references to `Iterator`, `IntoIterator`, `iter()`, and `into_iter()`.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.