Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust, is a vector an Iterator?

Tags:

iterator

rust

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.

like image 352
Ralph Caraveo Avatar asked Apr 17 '16 04:04

Ralph Caraveo


People also ask

What is iterator in Rust?

An iterator is responsible for the logic of iterating over each item and determining when the sequence has finished. When you use iterators, you don't have to reimplement that logic yourself. In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up.

What is a vector in Rust?

Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O(1) indexing and push and pop operations in vector also take O(1) complexity.

What is an iterator in vector?

Vector's iterators are random access iterators which means they look and feel like plain pointers. You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [] . std::vector<int> vec(10); std::vector<int>::iterator it = vec.

Can we use iterator in vector?

Use an iteratorAn iterator can be generated to traverse through a vector. vector<int>::iterator iter; An iterator is used as a pointer to iterate through a sequence such as a string or vector . The pointer can then be incremented to access the next element in the sequence.


1 Answers

No, a vector is not an iterator.

But it implements the trait IntoIterator, which the for loop uses to convert the vector into the required iterator.

In the documentation for Vec you can see that IntoIterator is implemented in three ways:

  • for Vec<T>, which is moved and the iterator returns items of type T,
  • for a shared reference &Vec<T>, where the iterator returns shared references &T,
  • and for &mut Vec<T>, where mutable references are returned.

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

like image 187
starblue Avatar answered Sep 28 '22 07:09

starblue