Didn't expect rust to support dropping outer variables in a loop

⚓ Rust    📅 2026-06-19    👤 surdeus    👁️ 1      

surdeus

This actually compiles: (note the drop(writer) inside a for loop)

let mut batches = Vec::new();
let mut ty = hecs::ColumnBatchType::new();
ty.add::<i32>();

let batch_size = 32;
let mut builder = ty.clone().into_batch(batch_size);

let mut writer = builder.writer::<i32>().unwrap();

for i in 0..10 {
    if let Err(v) = writer.push(i) {
        drop(writer);

        let old_builder = std::mem::replace(&mut builder, ty.clone().into_batch(batch_size));
        batches.push(old_builder.build().unwrap());

        writer = builder.writer::<i32>().unwrap();

        writer.push(v).unwrap();
    }
}

drop(writer);
batches.push(builder.build().unwrap());

New knowledge learned:
I can drop a Non-Copy value inside a loop as long as I re-assign it later.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed