Rust Reference ยท Iterators
The ExactSizeIterator trait
Reference for the Rust ExactSizeIterator trait: the len() method, which iterators know their exact length, why filter does not, and how to implement it.
ExactSizeIterator marks an iterator that knows precisely how many items remain. It adds a single useful method, len(), which returns that number without consuming anything. Slices, vectors, ranges of integers, map over one of those, enumerate, zip and rev of such iterators all qualify.
The trait is a promise about size_hint: for an exact-size iterator the lower and upper bounds are both equal to the true remaining length. It is also what lets enumerate().rev(), rposition and collect pre-allocate exactly. Iterators whose length depends on running a predicate, such as filter, take_while and chars(), cannot offer it.
pub trait ExactSizeIterator: Iterator { fn len(&self) -> usize { /* from size_hint */ } }
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
pub trait ExactSizeIterator: Iterator { fn len(&self) -> usize; }
| Name | Description |
|---|---|
len |
The number of items left. The default implementation reads size_hint, asserts that both bounds are equal and returns that value. |
Returns: the exact remaining item count; it shrinks as you consume the iterator.
Panics: the default len panics (in an assertion) if size_hint does not return (n, Some(n)). That is a bug in the iterator, not in the caller.
Usage notes
- Implementing it is one line (
impl ExactSizeIterator for T {}) provided you overridesize_hintwith exact bounds. Usually you do not overridelenitself. - Do not lie. A wrong
size_hintdoes not cause undefined behavior in safe code, butlen()can panic andcollectmay allocate the wrong amount. Unsafe code must never rely on the hint being correct unless the iterator isTrustedLen, an unstable internal trait. - The
usizelimit. An inclusive range such as1..=5ofi32is not exact-size, because ranges that could hold more thanusize::MAXitems cannot promise ausizelength. OnlyRangeInclusiveof 8- and 16-bit integers qualify; use1..6when you needlen(). - It differs from
count().count()consumes the iterator and runs it to the end;len()is O(1) for the standard types and leaves the iterator intact. - There is no
is_emptymethod on stable. Writeit.len() == 0. (ExactSizeIterator::is_emptyis unstable.) - Use it as a bound when your function needs the count up front, for instance to size an output buffer or print "3 of 10".
rpositionandenumerate().rev()needExactSizeIterator + DoubleEndedIteratorbecause the indexes have to be known before the first item is taken from the back.