Mojo trait
AnyType
A trait for types that require lifetime management through destructors.
The AnyType
trait is fundamental to Mojo's memory management system. It indicates
that a type has a destructor that needs to be called when instances go out of scope.
This is essential for types that own resources like memory, file handles, or other
system resources that need proper cleanup.
Key aspects:
- Any type with a destructor must implement this trait
- The destructor (
__del__
) is called automatically when an instance's lifetime ends - Composition of types with destructors automatically gets a destructor
- All Mojo structs and traits inherit from
AnyType
by default unless they specify@explicit_destroy
Example:
struct ResourceOwner(AnyType):
var ptr: UnsafePointer[Int]
fn __init__(out self, size: Int):
self.ptr = UnsafePointer[Int].alloc(size)
fn __del__(deinit self):
# Clean up owned resources
self.ptr.free()
Best practices:
- Implement this trait when your type owns resources that need cleanup
- Ensure the destructor properly frees all owned resources
- Consider using
@explicit_destroy
for types that should never have destructors - Use composition to automatically handle nested resource cleanup
Implemented traits
Aliases
__del__is_trivial
alias __del__is_trivial
A flag (often compiler generated) to indicate whether the implementation of __del__
is trivial.
The implementation of __del__
is considered to be trivial if:
- The struct has a compiler-generated trivial destructor and all its fields
have a trivial
__del__
method.
In practice, it means that the __del__
can be considered as no-op.
Methods
__del__
__del__(var self: _Self, /)
Destroys the instance and cleans up any owned resources.
This method is called automatically when an instance's lifetime ends. It receives an owned value and should perform all necessary cleanup operations like:
- Freeing allocated memory
- Closing file handles
- Releasing system resources
- Cleaning up any other owned resources
The instance is considered dead after this method completes, regardless of whether any explicit cleanup was performed.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!