Emulating eagerly dropping of values

In Mojo, the destructor is run eagerly, as opposed to Rust and C++, whose destructors only run at the end of the value's scope.

Quote from Mojo's programming manual:

Mojo destroys values like MyString (it calls the del() destructor) using an “As Soon As Possible” (ASAP) policy that runs after every call. Mojo does not wait until the end of the code block to destroy unused values. Even in an expression like a+b+c+d, Mojo destroys the intermediate expressions eagerly, as soon as they are no longer needed—it does not wait until the end of the statement. [Omitted...] The Mojo compiler automatically invokes the destructor when a value is dead and provides strong guarantees about when the destructor is run. Mojo uses static compiler analysis to reason about your code and decide when to insert calls to the destructor.

Is there a way to emulate this eager dropping in Rust?

Not without being explicit about it. Here's a recent thread on the topic.

And some notes off the top of my head,

  • It can't be perfect and happen 100% at compile time as whether or not something has been dropped at runtime (e.g. in a conditional block) is undecidable in the general case

  • Depending on exactly what you wanted to drop when, it may require lifetimes to influence code generation, which is considered something which is not allowed

Alright then, since there is another thread not long ago discussing this, let's close this particular topic.