The code below has 2 distinct while loops I used in some of my code. I was expecting the same behaviors but eventually realized that somehow the "&&" in the second while loop did not behave as I expected. See:
use std::collections::HashSet;
fn main() {
let mut hs = HashSet::new();
let arr = [Some(2), Some(3)];
let mut iter = arr.iter();
while let Some(m) = iter.next() {
hs.insert(m);
}
println!("HashSet ==> {:?}", hs);
hs.clear();
while let Some(m) = iter.next()
&& hs.insert(m)
{
println!("{:?}", m);
}
println!("HashSet ==> {:?}", hs);
}
The first while loop has a condition that obviously evaluates to True since it insert both values from the vector:
let Some(m) = iter.next()
I was expecting the second while loop to behave the SAME way since combining the first expression (the let) with "&& hs.insert(m)" would also evaluate to True.
The first while-loop consumed all the elements of the iterator. You tried to continue iterating over the same iterator… but it was already exhausted, so since slice iterators (used by [T], [T; N], Vec<T>, and probably plenty of other types too) are “fused” iterators (see the FusedIterator trait), once they reach the end of the slice, they stay exhausted.
No apologies are needed. Posts like this are useful for those of us who like to help, and who work on rustc to make it more helpful, by letting us learn about what kinds of mistakes people make.