Uses for Iterator that return Some(_) after None?

While reading the official documentation about Iterator's next method, I found out this note:

Individual iterator implementations may choose to resume iteration, and so calling next() again may or may not eventually start returning Some(Item) again at some point.

I've never used any iterator that had this behavior, and I was wondering, does it have any meaningful uses (for example iterating once, reaching the end, re-iterating and obtaining different values), or is this note just saying that methods that work with iterators should not rely on the iterator's next method returning None forever at the end of the iterator ?

I think signaling "end of file" can sometimes be transient, e.g. if you press CTRL-D in a terminal window, it may send an "end of file" condition. But it's still possible to enter data afterwards.

Some polling actions can present an iterator-like interface. Those don't necessarily yield something every time.

I can also imagine that some implementors would have to make an extra effort to "remember" if the iterator was exhausted. That's what Iterator::fuse is for, if you want to handle that problem on a case-by-case basis. See also FusedIterator, which you can implement if you already know that None is always the end. (Also note that FusedIterator is not an unsafe trait, thus fuse cannot be relied upon in unsafe blocks.)

Here's one concrete example of an iterator that intentionally can return Some after None: Notifications in postgres::notifications - Rust

1 Like

What do you mean by this? Traits don't need to be marked unsafe to be used in unsafe blocks.

What he meant was that the soundness of your unsafe code must not depend on the correct/incorrect implementation of FusedIterator.

This is because you can, in safe code, write a FusedIterator that does in fact return Some after a None.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.