Are all iterators lazy?

From the documentation of BTreeSet:

Difference
A lazy iterator producing elements in the difference of BTreeSets.
ExtractIf
An iterator produced by calling extract_if on BTreeSet.
Intersection
A lazy iterator producing elements in the intersection of BTreeSets.
IntoIter
An owning iterator over the items of a BTreeSet in ascending order.
Iter
An iterator over the items of a BTreeSet.
Range
An iterator over a sub-range of items in a BTreeSet.
SymmetricDifference
A lazy iterator producing elements in the symmetric difference of BTreeSets.
Union
A lazy iterator producing elements in the union of BTreeSets.

Why “lazy” ? Isn’t it the case that all Rust iterators are “lazy”? Is there some subtle distinction I am missing here?

Yes. The doc comments you are referring to were originally created pre-1.0 Rust, maybe back then eager iterators were a thing, I don't know.

2 Likes

I think it might just be there to clarify that the set operation itself is lazy.

1 Like

Yes, that does seem to be the pattern, maybe because it could be surprising I suppose.

Sometimes when an iterator is described as being lazy, it means that nothing is accessed in the underlying collection until you call for a value. I remember this distinction from Scala; IIRC their iterator for a Stream tried to preload the first value, which could in theory cause side effects or even an exception. I have no idea whether that distinction is relevant to BTreeSets.

Note that things that aren't iterators, but can kind of be treated like them sometimes are not covered by the blanket "yes".

This has tripped me a few times:

let option = Some(whatever);
option.map(f); // Not lazy
option.iter().map(f); // Lazy
2 Likes

BTreeSet::difference does do some processing on construction of the iterator, including calling element comparison functions (which could panic), so I don’t think this what it means.

"Owning iterator" in that listing, on the other hand, is important - it means that on Drop, the iterator will be exhausted and all values destroyed.