Values, Text and Callbacks · 14 min · free with an account

Iterator Ownership and Laziness

Lesson preview · about 30%

An iterator pipeline describes work; the item type and terminal operation determine ownership and execution.

Core idea

Trace the receiver, iterator item type and consumer before making a move or allocation claim.

Start with the idea

For a Vec<T>, iter normally yields &T, iter_mut yields &mut T and into_iter on an owned vector yields T. The chosen receiver matters: into_iter on a reference can still borrow. Read the actual item type before deciding whether an operation moves, copies or clones values.

Most iterator adapters are lazy. map describes a transformation, while a consumer such as collect or sum drives it. Returning an iterator can avoid collecting an intermediate vector, but keeps any captured input borrows alive for the returned iterator’s lifetime.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 754 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep