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.
let v: Vec<i32> = (1..=4).rev().collect(); // [4, 3, 2, 1] let end = [1, 2, 3].iter().last(); // Some(3)
Try it
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.
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
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
revis lazy and free. It just swaps the roles ofnextandnext_back; nothing is copied or allocated.last()consumes the whole iterator for most types (it callsnextuntil it runs out, O(n)). On slices and ranges, specialized implementations can be faster, butslice.last()(the slice method returningOption<&T>) is always O(1) and the better choice.- Order of adapters matters:
enumerate().rev()keeps the original indexes (descending), whilerev().enumerate()numbers the reversed sequence from 0.revafterenumeraterequiresExactSizeIteratoras 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;charreversal is fine for ASCII data and algorithm exercises.chain,zipandmapkeep double-endedness when their parts have it;filterdoes too, butskip_while,take_whileandscando not.- Reverse sort without
rev: usesort_by(|a, b| b.cmp(a))orsort_by_key(|x| Reverse(...)); reversing after sorting costs an extra pass.