0

In Chapter 4 of The Rust Programming Language, the drop function is introduced as being implicitly called at the end of any scope on all the variables that were allocated within that scope. This solves the usual alloc/dealloc problems.

I can imagine wanting to drop earlier in some situations though. This question explains how to explicitly force a drop, and it's also possible to force deallocation early through the declaration of an inner scope:

let mut b = cheap_default_initialization();
{ 
    let a = some_large_allocation();
    b = some_other_large_allocation(a);
    some_other_work(a, b);
}
let c = third_large_allocation(b);

However, the explicit call to drop seems awkward, since one of the purposes of the ownership system is to avoid explicit, error prone, deallocation by the programmer. The inner scope solution seems more elegant, but also can require mutation that would otherwise be unnecessary (as shown in the example).

Is there more idiomatic way to drop early than either of these? Is there a general agreement about which approach is better, or when each should be used?

4

0 回答 0