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?

John Doucette
  • 4,370
  • 5
  • 37
  • 61
  • 2
    "dangling reference bugs" - Is it still a bug if it won't compile? – Wesley Wiser Aug 02 '18 at 15:36
  • 1
    See also [Moved variable still borrowing after calling `drop`?](https://stackoverflow.com/questions/43428894/moved-variable-still-borrowing-after-calling-drop) – Shepmaster Aug 02 '18 at 15:37
  • 2
    AFAIK there's nothing un-idiomatic about calling `drop` explicitly but it has no special meaning to the borrow checker. Depending on your exact situation, `drop` may be appropriate or using a nested block may be appropriate. – Wesley Wiser Aug 02 '18 at 15:38
  • 1
    *whether there's a way to drop that avoids the explicit call* — but that's not the whole question, right? You've already identified that adding a new scope accomplishes the same goal, so presumably there are other restrictions you are adding? – Shepmaster Aug 02 '18 at 15:42
  • @Shepmaster Really what I'm looking for is the *idiomatic* way to express this. I'm not very familiar with the language as yet. I came up with a way to express what I wanted, but, when learning a new language the first way that comes to mind is often not the best. – John Doucette Aug 02 '18 at 15:44
  • 6
    There's really only one way to drop a value in Rust: let it fall out of scope. There's nothing special about the `drop()` function, it's literally implemented as `pub fn drop(_x: T) { }`. [The documentation explains this more.](https://doc.rust-lang.org/std/mem/fn.drop.html) – Wesley Wiser Aug 02 '18 at 15:58

0 Answers0