Rust

Lesson 07

Iterator ownership

Choose iter, iter_mut, or into_iter based on whether the code reads, mutates, or consumes collection items.

Good Code

src/review_counts.rs
pub fn approved_count(reviews: &[Review]) -> usize {
    // iter reads each review without moving the collection.
    reviews.iter().filter(|review| review.approved).count()
}

Bad Code

review_counts.rs
pub fn approved_count(reviews: Vec<Review>) -> usize {
    // into_iter consumes the vector even though the function only counts.
    reviews.into_iter().filter(|review| review.approved).count()
}

Review Notes

What to review

Good Code

The good version borrows a slice and uses iter, so callers keep the collection after the count.

Bad Code

The bad version takes Vec<Review> and consumes it with into_iter. A read-only operation now forces ownership transfer and may cause clones at the call site.

Takeaways

  • A Rust loop should make collection ownership visible through the iterator method it chooses.