TL;DR
- The iterator returned by
into_iter
may yield any ofT
,&T
or&mut T
, depending on the context. - The iterator returned by
iter
will yield&T
, by convention. - The iterator returned by iter_mut will yield &mut T, by convention.
The first question is: "What is into_iter
?"
into_iter
comes from the IntoIterator
trait:
You implement this trait when you want to specify how a particular type is to be converted into an iterator. Most notably, if a type implements IntoIterator
it can be used in a for
loop.
For example, Vec
implements IntoIterator
... thrice!
Each variant is slightly different.
This one consumes the Vec
and its iterator yields values (T
directly):
The other two take the vector by reference (don't be fooled by the signature of into_iter(self)
because self
is a reference in both cases) and their iterators will produce references to the elements inside Vec
.
This one yields immutable references:
While this one yields mutable references:
So:
What is the difference between
iter
andinto_iter
?
into_iter
is a generic method to obtain an iterator, whether this iterator yields values, immutable references or mutable references is context dependent and can sometimes be surprising.
iter
and iter_mut
are ad-hoc methods. Their return type is therefore independent of the context, and will conventionally be iterators yielding immutable references and mutable references, respectively.