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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With