How do you implement `ExactSizeIterator`?

I'm a bit confused by the documentation of ExactSizeIterator. As far as I understand, the only think I need to do it to implements the functions iter() and size_hint() when implementing Iterator. size_hint() should return (exact_size, Some(exact_size)) with exact_size being the exact number of elements that will be yielded.

The len() function doesn't need to be implemented and will just use size_hint().0 => Is this right, because the example implements len() and not size_hint().

Yes, you only need size hint. However, overriding len can improve performance.

Is it needed to redefine len() if size_hint() is just reading an usize (I store the remaining size in a attribute)?

It's never needed to redefine len, since it uses size_hint if you don't. If size_hint is just reading a struct field it will probably be inlined anyway so there's no point in optimizing it.

1 Like