Slightly surprising behavior of a while loop
⚓ Rust 📅 2026-05-16 👤 surdeus 👁️ 3The 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);
}
Running this code displays:
HashSet ==> {Some(2), Some(3)}
HashSet ==> {}
1 post - 1 participant
🏷️ Rust_feed