Understanding when and why temporary is dropped
⚓ Rust 📅 2025-10-18 👤 surdeus 👁️ 2The code below (and in Playground)
let v = vec![3i32, 2i32].iter();
println!("{}", v.sum::<i32>());
Errors due to a temporary being dropped.
I expected this would convert to something close to (but the last example contradicts it):
let v = {
let _tmp =vec![3i32, 2i32];
<[_]>::iter(&_tmp[..])
}; // underlying data is dropped after we exit block expression
But if that were the case, should happen the same here?
let f = move |a| a;
let v = f(&6);
println!("{v}")
But this runs fine.
So, what rule is being applied in terms of drop scope, in the first case? And in the second?
5 posts - 3 participants
🏷️ Rust_feed