Idea: &mut I where I:Iterator<Item=T> should be usable in for loops

I came across the want to have a single iterator that was passed between functions as a mutable reference so that the progress would be tracked by the iterator. However, I found it very strange that I had to use a while let loop instead of being able to use a for loop.

I know that I could not deference the reference because that would be “moving out of a borrowed context” however it makes sense, to me at least, that a for loop should be able to iterate over a mutable reference of an iterator, given that next(&mut self).

You can use &mut I in for loops, because of this:

impl<'_, I> Iterator for &'_ mut I where
    I: Iterator + ?Sized,

However, the for loop holds that borrow throughout the loop, which is why you can’t continue using the iterator elsewhere. Using a while let loop only borrows the iterator each time that expression is evaluated.


Ah I see, and this is certainly something that cannot be changed. Thank you

You might be interested in

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.