Unnecessary `drop_in_place` emitted for a fully consumed `IntoIter`
⚓ Rust 📅 2025-11-04 👤 surdeus 👁️ 5https://godbolt.org/z/h5hb758qj
pub struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) { panic!("dropped") }
}
pub fn test(items: Vec<(i32, Option<Bomb>)>) -> i32 {
let mut last = 0;
for (x, bomb) in items {
last = x;
std::mem::forget(bomb);
}
last
}
In the test function, the loop always fully consumes the vector, but the nightly compiler still generates another loop after the written loop for dropping the remaining items (there should be none). Is there any way to stop the compiler from generating it?
Interestingly, changing Option<Bomb> to Bomb stopped the compiler from generating the unnecessary drop code. Why does having an Option in the element type blocked this optimization?
2 posts - 2 participants
🏷️ Rust_feed