Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is List wrapped in IntoIter?

Tags:

iterator

rust

In the book Learning Rust With Entirely Too Many Linked Lists, in the implementation of IntoIter, why is List wrapped in a tuple struct? Instead, Iterator could have been implemented for a List.

like image 296
letmutx Avatar asked Dec 08 '25 14:12

letmutx


1 Answers

Yes, technically Iterator could be implemented for List in this case. This isn't generally true, since iterators might need different state that's not in the base container (e.g. a Vec iterator might need to store an index to the next item to iterate efficiently).

One reason is that if the implementation changes in future and the List iterator would be better with extra state, it's possible to change the iterator struct without changing any callers.

Another reason is that in Rust it's common to use types to narrow interfaces to reduce the chance of errors. If you implement Iterator directly (and presumably IntoIterator to return self), then that leaves the possibility for the user to call other List methods during iteration, which is probably wrong. Instead the iterator is a separate type, meaning that there's no possibility of someone pushing items on during iteration. (Note that in a for loop it'd be hard to do this anyway due to the borrowing/move rules, but the general point is still there).

like image 110
Chris Emerson Avatar answered Dec 11 '25 14:12

Chris Emerson