Skip to content

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.

A destructor takes self with the deinit convention, which means “this value is ending now”:

@fieldwise_init
struct 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.com
sending bye to example.com
closing connection to example.com
main 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.

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_init
struct 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.)

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_init
struct 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 door
working 1
working 2

The 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_init
struct 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 1
working 2
unlock door
after

_ = guard counts as a use, so guard now lives until that line. Think of it as “I’m done with this here”.

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_init
struct Wheel(Movable):
var pos: String
def __deinit__(deinit self):
print(" wheel", self.pos, "removed")
@fieldwise_init
struct 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 mini

The 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.

A destructor can’t raise an error. Mojo checks this:

@fieldwise_init
struct 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 module

Destructors 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.

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_init
struct 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:

opening
Dear reader

You 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.

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_init
struct 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 tickets
used ticket 7
refunded ticket 8

Now 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_init
struct 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 manager

When 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.

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_init
struct 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")
_ = t

Output:

step 1
step 2
download finished

_ = t moves the timer’s last use to the end, so its destructor runs after both steps.

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_init
struct 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:

unwrapping
I got a book

unwrap 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 _ = x to 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 deinit method for cleanup that can fail.
  • not Deinitable makes 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

1. A variable is last used on line 3 of a 10-line function. When does its destructor run?
2. What does _ = guard do?
3. Your cleanup can fail and should report an error. What should you use?
4. What happens when a not Deinitable value is left alone on one path through the code?