Skip to content
Tutorials Center
My learning

Topics

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.

Rust
pub trait ExactSizeIterator: Iterator {
    fn len(&self) -> usize { /* from size_hint */ }
}

Try it

Rust len on iterators

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 Implementing ExactSizeIterator

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
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 override size_hint with exact bounds. Usually you do not override len itself.
  • Do not lie. A wrong size_hint does not cause undefined behavior in safe code, but len() can panic and collect may allocate the wrong amount. Unsafe code must never rely on the hint being correct unless the iterator is TrustedLen, an unstable internal trait.
  • The usize limit. An inclusive range such as 1..=5 of i32 is not exact-size, because ranges that could hold more than usize::MAX items cannot promise a usize length. Only RangeInclusive of 8- and 16-bit integers qualify; use 1..6 when you need len().
  • 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_empty method on stable. Write it.len() == 0. (ExactSizeIterator::is_empty is 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".
  • rposition and enumerate().rev() need ExactSizeIterator + DoubleEndedIterator because the indexes have to be known before the first item is taken from the back.