Is it accurate to state that a vector (among other collection types) is an Iterator
?
For example, I can loop over a vector in the following way, because it implements the Iterator
trait (as I understand it):
let v = vec![1, 2, 3, 4, 5];
for x in &v {
println!("{}", x);
}
However, if I want to use functions that are part of the Iterator
trait (such as fold
, map
or filter
) why must I first call iter()
on that vector?
Another thought I had was maybe that a vector can be converted into an Iterator
, and, in that case, the syntax above makes more sense.
No, a vector is not an iterator.
But it implements the trait
IntoIterator
, which thefor
loop uses to convert the vector into the required iterator.In the documentation for
Vec
you can see thatIntoIterator
is implemented in three ways:Vec<T>
, which is moved and the iterator returns items of typeT
,&Vec<T>
, where the iterator returns shared references&T
,&mut Vec<T>
, where mutable references are returned.iter()
is just a method inVec
to convertVec<T>
directly into an iterator that returns shared references, without first converting it into a reference. There is a sibling methoditer_mut()
for producing mutable references.