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

#1

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).

0 Likes

#2

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.

5 Likes

#3

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

0 Likes

#4

You might be interested in http://blog.ssokolow.com/archives/2017/06/23/rust-looping-on-a-member-variable-without-mutably-borrowing-self/

1 Like