Mojo Destructors
A destructor is the code that runs when a value is destroyed. In Mojo it’s a method called __deinit__. Most structs don’t need one: Mojo destroys their fields for you. You write one when your struct holds something that needs cleaning up, like a file to close, memory to free or a connection to end. This page shows how to write one, exactly when it runs, and what to do when “as soon as possible” is too soon.
Writing a destructor
Section titled “Writing a destructor”A destructor takes self with the deinit convention, which means “this value is ending now”:
@fieldwise_initstruct Connection(Movable): var host: String
def send(self, msg: String): print("sending", msg, "to", self.host)
def __deinit__(deinit self): print("closing connection to", self.host)
def main(): var conn = Connection("example.com") conn.send("hello") conn.send("bye") print("main keeps going")Output:
sending hello to example.comsending bye to example.comclosing connection to example.commain keeps going(It’s not a real network connection, just a print, so you can see when cleanup happens.) You never call __deinit__ yourself. Mojo calls it once, at the right moment. Inside it, self and its fields are still valid, so you can read self.host.
In Python, the closest thing is __del__, but Python doesn’t promise when __del__ runs, or even that it runs at all. Mojo’s destructor runs at a moment you can predict from the code.
When it runs: right after the last use
Section titled “When it runs: right after the last use”Look at the output again: the connection closed before main keeps going. Mojo destroys a value right after its last use, not at the end of the block. The last use of conn was conn.send("bye"). This is called ASAP destruction, and the manual’s page on automatic destruction explains the rules.
It even applies inside a single expression. Temporary values that never get a name are destroyed as soon as they’ve been used:
@fieldwise_initstruct Number(Writable): var value: Int
def __deinit__(deinit self): print(t"Destroying Number({self.value})")
def __add__(self, other: Number) -> Number: return Number(self.value + other.value)
def __mul__(self, other: Number) -> Number: return Number(self.value * other.value)
def main(): var a = Number(2) var b = Number(3) var c = Number(4) print(a + b * c)Output:
Destroying Number(4)Destroying Number(3)Destroying Number(12)Destroying Number(2)Number(value=14)Destroying Number(14)b * c runs first and makes a temporary Number(12). After that, b and c aren’t needed, so they go. Then a + Number(12) makes Number(14), and a and the temporary 12 go. Number(14) lives until print is done with it. (Writable is what lets print show the struct; see Mojo Printing Your Types.)
When ASAP is too soon
Section titled “When ASAP is too soon”Most of the time, early cleanup is exactly what you want: memory is freed as early as possible. But sometimes a value does its job just by existing. Think of a lock that should stay locked while you work:
@fieldwise_initstruct Lock(Movable): var name: String
def __deinit__(deinit self): print("unlock", self.name)
def main(): var guard = Lock("door") print("working 1") print("working 2")Output:
unlock doorworking 1working 2The door is unlocked before any work happens! guard is never used after it’s created, so its last use is its creation. (Mojo even warns: assignment to 'guard' was never used; assign to '_' instead?)
The fix is to mark where the value’s life should end, by assigning it to _:
@fieldwise_initstruct Lock(Movable): var name: String
def __deinit__(deinit self): print("unlock", self.name)
def main(): var guard = Lock("door") print("working 1") print("working 2") _ = guard print("after")Output:
working 1working 2unlock doorafter_ = guard counts as a use, so guard now lives until that line. Think of it as “I’m done with this here”.
What happens to the fields
Section titled “What happens to the fields”After your __deinit__ code, Mojo destroys the struct’s fields for you. You don’t free a String or List field by hand. Fields follow ASAP destruction too, even inside __deinit__:
@fieldwise_initstruct Wheel(Movable): var pos: String
def __deinit__(deinit self): print(" wheel", self.pos, "removed")
@fieldwise_initstruct Car(Movable): var name: String var front: Wheel var back: Wheel
def __deinit__(deinit self): print(" scrapping", self.name)
def main(): var car = Car("mini", Wheel("front"), Wheel("back")) print("driving the", car.name)Output:
driving the mini wheel front removed wheel back removed scrapping miniThe wheels go before scrapping mini is printed, because the car’s destructor never uses them. self.name is used by the print, so it lives until after that line. If your cleanup depends on a field, use the field in __deinit__ and it’ll still be there.
Destructors can’t fail
Section titled “Destructors can’t fail”A destructor can’t raise an error. Mojo checks this:
@fieldwise_initstruct Thing(Movable): var n: Int
def __deinit__(deinit self) raises: print("bye")
def main(): var t = Thing(1)hello.mojo:5:9: error: destructor must not declare 'raises'; remove the 'raises' keyword def __deinit__(deinit self) raises: ^mojo: error: failed to parse the provided Mojo source moduleDestructors run automatically, where there’s no try to catch anything. If your cleanup can fail (saving a file, committing to a database), use a named cleanup method instead, as shown next.
Named cleanup methods
Section titled “Named cleanup methods”Any method can take deinit self. Calling it ends the value’s life, and the normal __deinit__ does not run afterwards. A common use is a method that takes a value apart and hands back what was inside:
@fieldwise_initstruct Envelope(Movable): var letter: String
def __deinit__(deinit self): print("envelope thrown away")
def open(deinit self) -> String: print("opening") return self.letter^
def main(): var e = Envelope("Dear reader") var text = e^.open() print(text)Output:
openingDear readerYou call it as e^.open(): the ^ hands the envelope to the method, because it’s going to end it. Inside, self.letter^ moves the letter out (allowed, because self is ending anyway). “envelope thrown away” never prints: open replaced the destructor for this value.
Values that must be cleaned up by hand
Section titled “Values that must be cleaned up by hand”Sometimes you want the compiler to make sure cleanup is done on purpose. Mark the type not Deinitable, give it named deinit methods, and add a message saying what to call:
@fieldwise_initstruct Ticket(not Deinitable else "call 'use()' or 'refund()'"): var id: Int
def use(deinit self): print("used ticket", self.id)
def refund(deinit self): print("refunded ticket", self.id)
def main(): var t = Ticket(7) var u = Ticket(8) print("got tickets") t^.use() u^.refund()Output:
got ticketsused ticket 7refunded ticket 8Now Mojo won’t destroy a Ticket on its own. If any path through your code forgets to call use() or refund(), the program doesn’t compile:
@fieldwise_initstruct Ticket(not Deinitable else "call 'use()' or 'refund()'"): var id: Int
def use(deinit self): print("used ticket", self.id)
def refund(deinit self): print("refunded ticket", self.id)
def main(): var t = Ticket(7) if t.id > 5: t^.use()hello.mojo:13:5: error: 't' abandoned without being explicitly destroyed: call 'use()' or 'refund()' if t.id > 5: ^mojo: error: failed to run the pass managerWhen t.id is 5 or less, nothing ends the ticket, and Mojo catches that. This is called explicit destruction. Named deinit methods are also allowed to raise, which is why they’re the right tool for cleanup that can fail. The manual’s explicit destruction page has more patterns. The standard library uses this for raw memory allocations, as you’ll see in Mojo Unsafe Pointers.
Practice
Section titled “Practice”1. A timer that reports
Section titled “1. A timer that reports”Write a struct Timer with a label: String field and a __deinit__ that prints <label> finished. In main, create Timer("download"), print step 1 and step 2, and make sure download finished is printed after both steps.
Hint: without anything extra, the timer would be destroyed straight after it’s created.
Show solution
@fieldwise_initstruct Timer(Movable): var label: String
def __deinit__(deinit self): print(self.label, "finished")
def main(): var t = Timer("download") print("step 1") print("step 2") _ = tOutput:
step 1step 2download finished_ = t moves the timer’s last use to the end, so its destructor runs after both steps.
2. Unwrap a gift
Section titled “2. Unwrap a gift”Write a struct Gift with a field item: String. Give it a method unwrap(deinit self) -> String that prints unwrapping and returns the item. In main, unwrap a gift holding "a book" and print what you got.
Hint: call it with ^: g^.unwrap(), and move the field out with self.item^.
Show solution
@fieldwise_initstruct Gift(Movable): var item: String
def unwrap(deinit self) -> String: print("unwrapping") return self.item^
def main(): var g = Gift("a book") var inside = g^.unwrap() print("I got", inside)Output:
unwrappingI got a bookunwrap consumes the gift and moves its item out. After g^, the variable g is empty.
- A destructor is
def __deinit__(deinit self);__del__is the deprecated old name. - Mojo runs it right after the value’s last use (ASAP destruction), even for temporaries inside an expression.
- Use
_ = xto keep a value alive until a specific line, for locks, guards and timers. - Fields are destroyed for you, after (or during) your
__deinit__, as soon as they’re no longer used. - Destructors can’t raise; use a named
deinitmethod for cleanup that can fail. not Deinitablemakes the compiler insist that every value is cleaned up explicitly, on every path.
Next up: pointers, what a pointer is and how Pointer, OwnedPointer and ArcPointer work.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Automatic destruction: ASAP destruction, field destruction and lifetime extension with
_ = value. - Explicit destruction:
not Deinitable, named deinitializers and raising cleanup. - Deinitable trait: the standard library reference for types Mojo can destroy on its own.
- Mojo ownership cheat sheet: lifecycle methods and opting out of moves and destruction.