Disallow two simultaenous references from iterator

Is there anyway to create an iterator that would fail to compile when calling next on it while a previous result is still in scope?

So in code like the following:

let a = iter.next().unwrap();
let b = iter.next().unwrap();
*a = 0;
*b = 0;

The second call to next would fail.

I think there isn't cause the returned references have the lifetime of the iterator not of the next call but perhaps there's any way to do it?

The standard Iterator interface intentionally guarantees it to be always possible, and methods like .collect() rely on it.

You need a StreamingIterator instead streaming_iterator - Rust

4 Likes

thanks!

Any idea if this can be done safely returning a mutable reference instead of a read only one as StreamingIterator does? I can't see why not but surely there's a reason if this crate doesn't implement it already

1 Like

Yes, you could define an analogous trait that returned mutable references instead. Adding a separate trait was suggested here, but nobody has submitted an implementation yet: https://github.com/sfackler/streaming-iterator/issues/21

Constructing a single trait that supports both types of references as well as other reference-like types would require something like Generic Associated Types.

1 Like

I've implemented this in two different ways and posted about it here:

https://github.com/sfackler/streaming-iterator/issues/21

1 Like

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.