Iterator is similar to ForwardIterator of C++. What you want is a BidirectionalIterator, but Rust does not provide a trait similar to it because of a limitation in the type system.
As Matthieu M said in comments, the way an iterator is defined allows a reference to the yielded element to be kept. And that's a problem if the iterator produces mutable references, because moving forward and backward would allow multiples mutable references to the same element. One way to solve this problem would be to tie the lifetime of the yielded element with &mut self, so a call to next (or prev) would borrow self, but there is no way of doing it in a generic way (there is a RFC to add such capability).
Looking the Iterator trait definition:
pub trait Iterator { type Item; fn next<'a>(&'a mut self) -> Option<Self::Item>; // ... }
we can see that the lifetime of Self::Item is independent of 'a. What is necessary to solve the problem is:
pub trait Iterator { type Item<'a>; // hypothetical syntax fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>; // ... }
but that is not supported yet.
That said, one option is to use a external crate that use a specific iterator (that is, do not implement a trait). The linked_list crate provides a linked list implementation with Cursor, that allows forward and backward iteration:
use linked_list::LinkedList; use std::iter::FromIterator; fn main() { // LinkedList::cursor takes &mut self, so lst must be mutable let mut lst = LinkedList::from_iter(0..10); let mut c = lst.cursor(); c.next(); c.next(); c.next(); c.prev(); assert_eq!(1, *c.prev().unwrap()); }
Cursor does not allow a reference to the yielded element to be kept. The docs says:
A Cursor is like an iterator, except that it can freely seek back-and-forth, and can safely mutate the list during iteration. This is because the lifetime of its yielded references is tied to its own lifetime, instead of just the underlying list. This means cursors cannot yield multiple elements at once.
The following example:
let a = c.next(); let b = c.next();
generates this error:
error: cannot borrow `c` as mutable more than once at a time [E0499] let b = c.next();
This happens because next (and prev) borrows from self, that is:
fn next<'a>(&'a mut self) -> Option<&'a mut T>
.rev()probably does not what you expect. It reverses the iterator, so you are now taking elements from the back.