From what I understand, the compiler automatically generates code to call the destructor to delete an object when it's no longer needed, at the end of scope.
In some situations, it is beneficial to delete an object as soon as it's no longer needed, instead of waiting for it to go out of scope. Is it possible to call the destructor of an object explicitly in Rust?
Yes.
No.
To clarify, you can use
std::mem::drop
to transfer ownership of a variable, which causes it to go out of scope:However, you are forbidden from calling the destructor (the implementation of the
Drop
trait) yourself. Doing so would lead to double free situations as the compiler will still insert the automatic call to the theDrop
trait.Amusing side note — the implementation of
drop
is quite elegant:The official answer is to call
mem::drop
:However, note that
mem::drop
is nothing special. Here is the definition in full:That's all.
Any function taking ownership of a parameter will cause this parameter to be dropped at the end of said function. From the point of view of the caller, it's an early drop :)