Version: 1.1.0
Automatic destruction
When a value is no longer used, Mojo destroys it. You write a destructor only when the struct owns a resource the compiler cannot see.
Essentials
- The last use is the destruction point.
__del__(owned self)runs custom cleanup.- Fields are destroyed after the destructor body.
- Copies and transfers decide which name runs the destructor.
- A collection destroys its elements.
Example
struct File:
var handle: Int
fn __del__(owned self):
if self.handle != 0:
close(self.handle)
Keep in mind
Do not call a destructor by hand on a type that Mojo already destroys. That frees the resource twice.