From the rust std doc there are 3 ways to get an iterator from a collection out of which 1 is provided by the IntoInter trait. Why iter()
and iter_mut()
do not have traits for them ? Is it a convention that collections needs to provide an iter()
/iter_mut()
method ? in which case why cant the convention become a trait in the std library ? I did not come across any trait that provides the 2 methods iter()
/iter_mut()
within the rust std library. Is this intentional by design ? in which case what was the reason behind this decision ?
1 Like
IntoIterator
is that trait. The trick is that it's implemented for references to those collections.
(&vec).into_iter()
gets you the same iterator asvec.iter()
.(&mut vec).into_iter()
gets you the same iterator asvec.iter_mut()
.
There are a lot of things enabled by trait implementations on references and other pointer types.
5 Likes
@kpreid Thank you. It just occurred to me that traits implemented on T
is different from traits implemented on &T
and &mut T
. Its very subtle and fine observation to make.
For those following this thread please take a look at the following:
1 Like
Another reason is that separate traits for iter(&self) -> Iter<'_>
and iter_mut
require GATs, but GATs are much newer than those APIs.
1 Like
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.