In Rust, why do .rev() and .len() fail to compile on a custom ID-block iterator, and what do DoubleEndedIterator and ExactSizeIterator require of it?
answer
- rev has a trait bound
- len is not on Iterator
- next_back meets next in the middle
- len trusts size_hint
- why Range<u64> has no len
basics
~20 srev requires DoubleEndedIterator (E0277 without it) and len exists only on ExactSizeIterator (E0599). Implement next_back for the first; for the second, make size_hint return the exact count and add an empty impl, or the default len panics.
solid answer
~50 s`Iterator::rev` carries the bound `Self: DoubleEndedIterator`, so on a plain iterator rustc reports E0277; `len` is not an `Iterator` method at all, so rustc reports E0599, no method named `len`. `DoubleEndedIterator` requires `next_back`, which takes from the back of the same range `next` takes from the front; the two must never cross, and iteration ends when they meet. `ExactSizeIterator` has no required methods: its default `len` reads `size_hint` and asserts that the upper bound equals `Some(lower)`, so an impl that keeps the default `(0, None)` compiles and then panics on the first `len()`. The contract is that `size_hint` is exact and `len` counts exactly the remaining `Some`s; because the trait is safe, unsafe code must not rely on it. That is also why `Range<u64>` is not `ExactSizeIterator`: its length may not fit in `usize` on a 32-bit target.
code
rust · 41 linesuse std::iter::FusedIterator;
/// `remaining` IDs reserved from the sequence, starting at `front`.
struct IdBlock { front: u64, remaining: usize }
impl Iterator for IdBlock {
type Item = u64;
fn next(&mut self) -> Option<u64> {
if self.remaining == 0 { return None; }
self.remaining -= 1;
self.front += 1;
Some(self.front - 1)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
impl DoubleEndedIterator for IdBlock {
fn next_back(&mut self) -> Option<u64> {
if self.remaining == 0 { return None; }
self.remaining -= 1;
Some(self.front + self.remaining as u64)
}
}
impl ExactSizeIterator for IdBlock {} // len() comes from size_hint
impl FusedIterator for IdBlock {}
fn main() {
let mut block = IdBlock { front: 100, remaining: 5 };
assert_eq!(block.len(), 5);
assert_eq!(block.next(), Some(100));
assert_eq!(block.next_back(), Some(104));
assert_eq!(block.len(), 3);
let newest_first: Vec<u64> = block.rev().collect();
println!("{newest_first:?}"); // [103, 102, 101]
let numbered: Vec<(usize, u64)> =
IdBlock { front: 1, remaining: 3 }.enumerate().rev().collect();
println!("{numbered:?}"); // [(2, 3), (1, 2), (0, 1)]
}go deeper
Know that rev and len need extra traits beyond Iterator: DoubleEndedIterator for rev and ExactSizeIterator for len.
Explain next_back and the meet-in-the-middle rule, and why the empty ExactSizeIterator impl depends on an exact size_hint.
Diagnose the len panic from a default size_hint, explain why Range<u64> and Chain are not exact, and state that unsafe code must not trust the trait.
Decide which refinement traits a public iterator type commits to, since removing an impl later breaks callers who rely on rev or len.
## Two errors, two different causes Take an iterator over a block of IDs reserved from a sequence, written with only `Iterator::next`. Two calls fail differently: - `block.rev()` — `rev` is a provided method of `Iterator`, but its signature says `where Self: Sized + DoubleEndedIterator`. rustc finds the method and rejects the call with **E0277**, "the trait bound `IdBlock: DoubleEndedIterator` is not satisfied". - `block.len()` — `len` is not on `Iterator` at all; it belongs to `ExactSizeIterator`. rustc finds no method and reports **E0599**, "no method named `len` found for struct `IdBlock` in the current scope". Both are fixed by implementing a **refinement trait** — a trait whose supertrait is `Iterator` and which unlocks extra methods. ## DoubleEndedIterator: taking from the back `DoubleEndedIterator` has one required method, `fn next_back(&mut self) -> Option<Self::Item>`. std's documentation states the rule: front and back work on the **same range and do not cross**; iteration is over when they meet in the middle. For an ID block that means: 1. `next` takes the lowest remaining ID and shrinks the block from the front. 2. `next_back` takes the highest remaining ID and shrinks it from the back. 3. Both return `None` once nothing remains, whichever end was used. Mixing the ends is legal and common: `block.next()` followed by `block.next_back()` takes the lowest and the highest ID, and the remaining count drops by two. An implementation that keeps separate front and back counters without checking that they met would hand out the same ID twice — exactly the crossing the documentation forbids. With `next_back` in place you get `rev`, `rfind`, `rfold`, `nth_back` and `next_back` itself, and adapters forward the capability: `Map<I, F>` is double-ended when `I` is, and `Enumerate<I>` is double-ended when `I` is both `DoubleEndedIterator` and `ExactSizeIterator`, because it must know the index of the last item. ## ExactSizeIterator: a promise, not a method `ExactSizeIterator` has **no required methods**. Its documentation says that the implementation of `Iterator::size_hint` *must* return the exact size, and that `len` returns exactly how many more times `Some` will come before `None`. The default `len` is built on that promise: ```rust fn len(&self) -> usize { let (lower, upper) = self.size_hint(); assert_eq!(upper, Some(lower)); lower } ``` So the classic mistake is to write `impl ExactSizeIterator for IdBlock {}` and forget `size_hint`. The default `size_hint` returns `(0, None)`; the code compiles, and the first `len()` panics with "assertion `left == right` failed", left `None`, right `Some(0)`. | Piece | Who writes it | Requirement | |---|---|---| | `size_hint` | you, on `Iterator` | returns `(n, Some(n))` with `n` the remaining count | | `len` | provided | override only for a faster exact count | | `is_empty` | unstable on this trait | not available on stable | The trait is **safe**, so a wrong `size_hint` is a logic bug, never undefined behaviour — and for the same reason `unsafe` code **must not** rely on it. The unstable, unsafe `TrustedLen` trait is std's internal way to carry a guarantee unsafe code may trust. Override `len` only when you can compute the count more cheaply than `size_hint` does; otherwise the default is the right choice. Since `is_empty` on this trait is unstable, stable code writes `len() == 0`. ## Why some std iterators are not exact The count must fit in a `usize`. std implements `ExactSizeIterator` for `Range<T>` only where `T` is no wider than `usize` on every target — `u8`, `u16`, `usize` and their signed forms, plus `u32` and `i32`, which the source admits are wrong on 16-bit targets but kept because removing them would break code stable since 1.0. `Range<u64>` gets no impl, so `(0..5u64).len()` is E0599. Adapters that may make an iterator longer give up the trait too: `Chain<A, B>` is not `ExactSizeIterator` even when both halves are, and `Filter` cannot know its count at all. ## Designing the ID block - Store the remaining count as a `usize` field, so `size_hint` is trivially exact and no cast can truncate. - Implement `next`, `size_hint` and `next_back`, then add the empty `impl ExactSizeIterator for IdBlock {}`. - Since the block returns `None` forever once empty, `impl FusedIterator for IdBlock {}` is honest and free. - Test the invariants: `len` before and after `next` and `next_back`, and `rev().collect()` producing the reverse order.
- Can unsafe code skip bounds checks because an iterator implements ExactSizeIterator?No. The trait is safe to implement, so any safe code can implement it wrongly. std's documentation says unsafe code must not rely on the correctness of `size_hint`; only the unstable, unsafe `TrustedLen` trait carries a guarantee unsafe code may depend on.
- Why is Chain<A, B> not ExactSizeIterator when both halves are?The combined length may exceed `usize::MAX`, for example when one half is already that long, and then no exact `usize` length exists. std's documentation gives this as the reason an adapter that makes an iterator longer usually should not implement the trait.
- Why does Enumerate::rev require ExactSizeIterator as well as DoubleEndedIterator?Reversed enumeration must pair the last item with the right index, so it needs to know how many items remain. The impl of `DoubleEndedIterator` for `Enumerate<I>` is bounded on `I: ExactSizeIterator + DoubleEndedIterator`.
- len is an Iterator method that counts by consuming the iterator.
- ExactSizeIterator requires you to write len yourself.
- A wrong size_hint in ExactSizeIterator is undefined behaviour.
- next_back may keep yielding after next has reached the same element.
- Every std range type supports len, including Range<u64>.