BorrowCheck › Rust language core

Collections and iterators

Choosing a collection, the Iterator trait and laziness, adapters and consumers, collect, into_iter forms, capacity.

The topic explains how to choose a standard library collection and how to work with its elements through iterators. The questions on collections check when Vec, VecDeque, HashMap or BTreeMap fits, why a key needs Eq and Hash, how entry does the job in a single lookup, and why a live reference from get_mut forbids insertion. The subtopic on the Iterator trait covers laziness: an adapter without a consumer does nothing, next requires a mutable binding, and by_ref keeps an iterator usable after a partial pass. The subtopic on adapters and consumers covers the order of filter and enumerate, the behavior of take_while, zip and rev, and overflow in sum in a debug build. Next come collect and the FromIterator trait, including collecting into a Result that stops at the first error, and the difference between the iter, iter_mut and into_iter forms, including arrays and the for loop. The last subtopic is about capacity and allocations: how a Vec grows, with_capacity, clear keeping its memory, and the role of size_hint.

41 questions: 22 basic, 17 intermediate, 2 advanced. 6 info pages, 24 sources.

Subtopics

  1. Choosing Vec, HashMap, BTreeMap
  2. The Iterator trait and laziness
  3. Adapters and consumers
  4. collect and FromIterator
  5. iter, iter_mut, into_iter
  6. Capacity and allocations

Previous: Associated types, GATs, const generics · Next: Closures