Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator rev, last and DoubleEndedIterator

Reference for reversing Rust iterators: rev, last, next_back, nth_back and rfind, which iterators are double-ended, and why chars().rev() is not grapheme-safe.

rev() reverses an iterator, so the last item comes first. It works on iterators that implement DoubleEndedIterator, meaning they can produce items from the back as well as from the front. Ranges, slices, Vec, chars(), BTreeMap and most adapters over them qualify.

last() is the opposite kind of question: it consumes the iterator and returns the final item. For a double-ended iterator, next_back() gets the same item without walking everything.

Rust
let v: Vec<i32> = (1..=4).rev().collect(); // [4, 3, 2, 1]
let end = [1, 2, 3].iter().last();         // Some(3)

Try it

Rust Reversing in loops and strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust last, next_back and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn rev(self) -> Rev<Self> where Self: DoubleEndedIterator;
fn last(self) -> Option<Self::Item>;

trait DoubleEndedIterator: Iterator {
    fn next_back(&mut self) -> Option<Self::Item>;
    fn nth_back(&mut self, n: usize) -> Option<Self::Item>;
    fn rfold<B, F>(self, init: B, f: F) -> B where F: FnMut(B, Self::Item) -> B;
    fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
        where P: FnMut(&Self::Item) -> bool;
}
Name Description
n How many items to skip from the back before returning one (0 is the last item).
init, f Starting value and combining closure for rfold, applied from the back.
predicate Test for rfind.

Returns: Rev<Self> for rev; Option<Item> for last, next_back, nth_back and rfind.

Errors / panics / edge cases: none panic. Calling rev() on a plain Iterator that is not double-ended is a compile error ("the trait bound ... DoubleEndedIterator is not satisfied"); lines() and split_whitespace() are double-ended, but std::iter::from_fn and successors are not.

Usage notes

  • rev is lazy and free. It just swaps the roles of next and next_back; nothing is copied or allocated.
  • last() consumes the whole iterator for most types (it calls next until it runs out, O(n)). On slices and ranges, specialized implementations can be faster, but slice.last() (the slice method returning Option<&T>) is always O(1) and the better choice.
  • Order of adapters matters: enumerate().rev() keeps the original indexes (descending), while rev().enumerate() numbers the reversed sequence from 0. rev after enumerate requires ExactSizeIterator as well, which slices and ranges are.
  • chars().rev() reverses code points, not what readers see. A base letter followed by a combining accent will end up with the accent attached to the wrong letter. Use a grapheme crate for user-facing text; char reversal is fine for ASCII data and algorithm exercises.
  • chain, zip and map keep double-endedness when their parts have it; filter does too, but skip_while, take_while and scan do not.
  • Reverse sort without rev: use sort_by(|a, b| b.cmp(a)) or sort_by_key(|x| Reverse(...)); reversing after sorting costs an extra pass.