Iterators and Ownership
CONCEPTS:Rust Iterators
Question Variations
- "Why does `map` not run until an iterator is consumed?"
- "What is the difference between `iter()`, `iter_mut()`, and `into_iter()`?"
- "When does an iterator pipeline allocate?"
- "How does `collect` know which collection to build?"
Why This Is Asked
Iterator pipelines are pervasive in Rust, and their ownership behavior affects both correctness and ergonomics. This question checks whether you know that adapters are lazy and can choose between consuming, immutable, and mutable iteration.
Key Concepts
- Iterator adapters such as
mapandfilterare lazy. - A consumer such as
collectorsumdrives the iterator. iter,iter_mut, andinto_iterborrow immutably, borrow mutably, or consume collection elements respectively.- Closures can capture surrounding values by borrow or move.
Question Variations
- “Why does
mapnot run until an iterator is consumed?” - “What is the difference between
iter(),iter_mut(), andinto_iter()?” - “When does an iterator pipeline allocate?”
- “How does
collectknow which collection to build?”