liveBook · Manning

Iter

As explained in Idiomatic Rust

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

`iter(&self)` lets callers visit a collection’s elements through immutable references without consuming the collection or exposing its internal structure. For a custom linked list, give iteration its own `Iter` type rather than implementing `Iterator` directly on the list. That keeps the collection and the state of a traversal separate. section 3.2.4

Choose the method by what the caller needs:

  • `iter(&self)` produces `&T` items for read-only access. section 3.2.4
  • `iter_mut(&mut self)` produces `&mut T` items for mutable access. section 3.2.4
  • `into_iter(self)` consumes the collection and produces `T` items. section 3.2.4

A linked-list implementation constructs `Iter` from its head pointer. The iterator tracks the next item; its `Iterator` implementation determines what each call to `next()` yields. An initial version returns a shared data wrapper rather than `&T`. The later reference-yielding version adds a lifetime and uses `PhantomData<&'a T>`; its shown `next()` implementation also uses `unsafe` to form the reference. Merely naming a method `iter` does not establish the promised item type. section 3.2.4

Read the list without consuming it

`dinosaurs.iter().for_each(|data| println!("data={}", data));` visits the list’s items through the read-only iterator. Implementing `IntoIterator` for `&LinkedList<T>` can delegate to `self.iter()`, enabling the equivalent borrowed form: `for data in &linked_list { println!("{data}"); }`. section 3.2.4

An iterator also makes the collection useful to other APIs. A `Debug` implementation can pass `self.iter()` to `Formatter::debug_list().entries(...)`, displaying list elements instead of the nested pointer structure. This mirrors familiar collection APIs while keeping traversal details out of callers’ code. section 6.11.4

How Idiomatic Rust covers it

How deep it goes
Works through a separate iterator type, traversal state, item types, lifetimes, and a reference-yielding `next()` implementation using `unsafe`.
Examples
Uses linked-list traversal with `for_each` and a borrowed `for` loop, plus `Formatter::debug_list().entries(self.iter())`.
What it assumes
Assumes familiarity with Rust traits, borrowing, and generic collections; develops the custom iterator and its lifetime handling through examples.
What you can do after
Build it from scratch for a linked list, then use it for borrowed loops and list-style debug output.
How it connects
Connects `Iterator`, `IntoIterator`, borrowing, lifetimes, `PhantomData`, and `Debug` formatting.

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.