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:
@value
struct ResourceOwner(AnyType):
var ptr: UnsafePointer[Int]
fn __init__(out self, size: Int):
self.ptr = UnsafePointer[Int].alloc(size)
fn __del__(owned self):
# Clean up owned resources
self.ptr.free()
@value
struct ResourceOwner(AnyType):
var ptr: UnsafePointer[Int]
fn __init__(out self, size: Int):
self.ptr = UnsafePointer[Int].alloc(size)
fn __del__(owned 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
UnknownDestructibility
Methods
__del__
__del__(owned 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!