In Rust, is a vector an Iterator?

Can it be argued that a vector (among other types of collections) is an Iterator ?

For example, I can iterate over a vector as follows, 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 attribute (e.g. fold , map or filter ), why should I first call iter() on this vector?

Another thought that I had was perhaps that the vector can be converted to Iterator , in which case the syntax above makes sense.

+7
iterator rust
source share
1 answer

No, the vector is not an iterator.

But it implements the IntoIterator trait that the for loop uses to convert the vector to the required iterator.

In the documentation for Vec you can see that IntoIterator is implemented in three ways: for Vec<T> , which moves the iterator returns elements of type T for the common link &Vec<T> , where the iterator returns the common links &T , and for &mut Vec<T> , where mutable links are returned.

iter() is just a method in Vec to convert Vec<T> directly to an iterator that returns shared links, without first converting it to a link. There is a sibling iter_mut() method for creating mutable links.

+20
source share

All Articles