Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse iterating over a &vec versus vec.iter()

Tags:

This works because Iterator implements rev() where self is a DoubleEndedIterator:

let vec: Vec<i32> = Vec::new();
for x in vec.iter().rev() {
    //Do stuff
}

However, if I change vec.iter().rev() to &vec.rev() it won't compile because:

no method named `rev` found for type `std::vec::Vec<i32>` in the current scope

Furthermore:

the method `rev` exists but the following trait bounds were not satisfied: `std::vec::Vec<i32> : std::iter::Iterator`, `[i32] : std::iter::Iterator`

But doesn't a for loop implicitly call IntoIterator? Is &vec or vec.iter() considered idiomatic Rust?

like image 574
HiDefender Avatar asked Sep 29 '16 16:09

HiDefender


People also ask

How do you reverse iteration?

Method #1 : Using reversed() The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting.

How do you iterate over a vector in reverse order?

So, to iterate over a vector in reverse direction, we can use the reverse_iterator to iterate from end to start. vector provides two functions which returns a reverse_iterator i.e. vector::rend() –> Returns a reverse iterator that points to the virtual element before the start of vector.

How do you reverse a list in a for loop?

3) Using for loop Another way to reverse the python list without the use of any built-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed.

How do you iterate through a reverse order on a map?

Now if we want to traverse it in reverse order we will use reverse_iterator of map. Syntax: map::reverse_iterator iterator_name; Reverse Iterator of map moves in backward direction on increment.


1 Answers

If you're just looping over the Vec, then &vec is idiomatic. This works because &Vec<T> implements IntoIterator, which is what the for loop uses.

However if you want to call Iterator methods such as rev, filter, etc., you need an actual Iterator (since Vec doesn't implement Iterator, only IntoIterator).

So this:

for x in &vec.rev() {
    ...
}

is equivalent to:

for x in (&vec.rev()).into_iter() {
    ...
}

i.e. there's no chance to use IntoIterator before trying to call Iterator methods.

like image 129
Chris Emerson Avatar answered Sep 20 '22 17:09

Chris Emerson