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
