Rust Reference ยท Iterators
Iterator enumerate and zip
Reference for Iterator::enumerate, zip and std::iter::zip in Rust: pairing items with indexes or with another iterator, unequal lengths, unzip, and common mistakes.
enumerate() turns an iterator of T into an iterator of (usize, T), numbering items from 0. It replaces the C-style counter variable and is the standard way to get an index in a for loop without indexing into the collection.
zip(other) walks two iterators in lockstep and yields tuples (a, b). It stops as soon as either side runs out, so the shorter one decides the length. Together they cover most "parallel iteration" needs without any indexing, and so without bounds checks or off-by-one errors.
for (i, name) in ["a", "b"].iter().enumerate() { println!("{i}: {name}"); }
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 enumerate(self) -> Enumerate<Self>; // Item = (usize, Self::Item) fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where U: IntoIterator; // Item = (Self::Item, U::Item) pub fn zip<A, B>(a: A, b: B) -> Zip<A::IntoIter, B::IntoIter> where A: IntoIterator, B: IntoIterator; // std::iter::zip
| Name | Description |
|---|---|
other |
Anything that implements IntoIterator, so you can pass &vec, a range or another adapter chain directly. |
Returns: a lazy iterator of tuples. Enumerate and Zip are exact-size and double-ended whenever their inputs are.
Edge cases: enumerate counts in a usize; it would panic (in debug builds) only after more than usize::MAX items, which cannot happen in practice. zip of unequal lengths drops the extra items silently, and may already have consumed one item from the longer iterator before noticing the other is finished.
Usage notes
std::iter::zip(a, b)(stable since Rust 1.59) reads better thana.into_iter().zip(b)when both sides are collections.- Tuple patterns in
for. Destructure directly:for (i, x) in v.iter().enumerate(). For nested zips the pattern mirrors the nesting:((a, b), c). enumerate().rev()versusrev().enumerate(). The first keeps the original indexes; the second renumbers from 0. Use the first when you need the position in the source.- Zip with an infinite iterator to number or label items:
names.iter().zip(1..). This is equivalent toenumeratestarting from 1. - Unequal lengths are not an error. If you need to detect them, compare the lengths first (for exact-size iterators,
a.len() == b.len()). - Windows of a slice are better served by
slice::windowsthan byzip(v.iter().skip(1)), although the latter works on any iterator. Iterator::unzipsplits an iterator of pairs into two collections. Seepartitionandunzip.