In addition to the examples @Michael-F-Bryan provided, it's typical for collections to provide methods with distinct names which yield those same iterators, for example if you own a LinkedList
then
list.into_iter()
will give you the owned iterator (over T
) via the trait
list.iter_mut()
will give you the exclusive borrow iterator (over &mut T
) via a method
list.iter()
will give you the shared borrow iterator (over &T
) via a method
The methods are more idiomatic and ergonomic in expression position than, say, (&list).into_iter()
. Where as was demonstrated above, for item in &list
is the more ergnomic (and idiomatic) approach when using for
. (What the pattern means is something you pick up when using Rust; you'll see it relatively frequently.)
&list
creates a shared reference to the list
and &mut list
creates an exclusive reference to the list
. They're similar to address-of operators. The reference calls them borrow operators.
This can happen automatically as part of method calls. In my bullet points above, list.iter()
creates a &list
to pass to LinkedList::iter
and list.iter_mut()
analogously creates a &mut list
.
The next question is, how did the compiler choose which methods to call?
To understand what methods are called in which situations and why it's unambiguous, you'll have to learn about method call resolution. The pertinent point when calling .into_iter()
is that if the type of the variable which is the operand of the method call (to the left of the .
) is a receiver of the method, that's the 'winner" of method call resolution. So
list.into_iter()
"sees" the implementation for the owned LinkedList
first
(&list).into_iter()
"sees" the implementation for &LinkedList
first
(&mut list).into_iter()
"sees" the implementation for &mut LinkedList
first
for
ultimately calls Intoiterator::into_iterator
on the in _
expression and works in the analogous fashion.
Whereas with list.iter()
, there is no method called iter
with a receiver of type LinkedList
, so the search continues. There is a method called iter
with a receiver of type &LinkedList
, and that's the winner.
list.iter_mut()
similarly finds no LinkedList
receiver method, also finds no &LinkedList
receiver method, but then does find the &mut LinkedList
receiver method called iter_mut
, so that's the winner.