Skip to content

Mojo Ownership

Python cleans up memory for you with a garbage collector: it counts who’s still using an object and frees it some time after nobody is. Mojo has no garbage collector. Instead, it follows a few simple ownership rules that the compiler checks while it builds your program. If you’ve never met ownership before, it can feel strange at first. This page takes it one rule at a time, with programs that print what’s happening so you can see it.

The Mojo manual’s ownership page sums it up like this:

  1. Every value has exactly one owner at a time. Usually the owner is a variable.
  2. When the owner’s life ends, Mojo destroys the value.
  3. While someone still has a reference to the value, the owner is kept alive.

That’s it. Everything else on this page, and in the next few lessons, follows from these three rules.

To see ownership in action, we need a value that tells us when it’s destroyed. A struct can have a special method called __deinit__ that Mojo runs when a value is destroyed. You’ll learn all about it in Mojo Destructors; for now, just know that the print inside it runs at the moment the value is cleaned up.

@fieldwise_init
struct Balloon(Movable):
var color: String
def __deinit__(deinit self):
print("pop!", self.color, "balloon is gone")
def main():
var red = Balloon("red")
print("I have a", red.color, "balloon")
var blue = Balloon("blue")
print("I have a", blue.color, "balloon")
print("end of main")

Output:

I have a red balloon
pop! red balloon is gone
I have a blue balloon
pop! blue balloon is gone
end of main

red owns the red balloon. Look at when it pops: not at the end of main, but right after the last line that uses red. Mojo works out the last use of every variable while compiling, and destroys the value straight after it. This is called ASAP destruction (as soon as possible).

If you know Python, this is the biggest surprise. In Python, an object usually lives until the end of the function. In Mojo, a value lives exactly as long as it’s needed.

A function that reads a value doesn’t need to own it. By default, it borrows a read-only reference, and the caller stays the owner:

@fieldwise_init
struct Balloon(Movable):
var color: String
def __deinit__(deinit self):
print("pop!", self.color, "balloon is gone")
def look_at(b: Balloon):
print("looking at the", b.color, "balloon")
def keep(var b: Balloon):
print("now I own the", b.color, "balloon")
def main():
var red = Balloon("red")
look_at(red)
print("back in main, still mine")
keep(red^)
print("end of main")

Output:

looking at the red balloon
back in main, still mine
now I own the red balloon
pop! red balloon is gone
end of main

Two different things happen here:

  • look_at(red) lends the balloon. look_at can read it, but main still owns it. When look_at returns, nothing is destroyed.
  • keep(red^) gives the balloon away. The var in front of the argument means “this function wants to own it”, and the ^ after red means “I’m handing it over”. Now keep is the owner, so the balloon pops when keep is done with it, before main prints its last line.

The ways a function can receive a value (borrow it, change it, own it) are called argument conventions. They get their own lesson: Mojo Argument Conventions.

The ^ sign is called the transfer sigil. It moves a value to a new owner, and the old variable becomes empty. Using it afterwards is an error:

@fieldwise_init
struct Balloon(Movable):
var color: String
def main():
var red = Balloon("red")
var friend = red^
print(red.color)
hello.mojo:8:10: error: use of uninitialized value 'red'
print(red.color)
^
hello.mojo:6:9: note: 'red' declared here
var red = Balloon("red")
^
mojo: error: failed to run the pass manager

“Uninitialized” means “has no value”. After var friend = red^, the balloon belongs to friend, and red is empty. This is rule 1 at work: there’s only ever one owner, so there’s no way for two variables to both think they own (and both destroy) the same balloon. Mojo Moving Values goes deeper into ^.

Ownership nests. A struct owns its fields, and a list owns its items. When the outer value is destroyed, everything it owns goes with it:

@fieldwise_init
struct Balloon(Movable):
var color: String
def __deinit__(deinit self):
print("pop!", self.color, "balloon is gone")
def main():
var party = List[Balloon]()
party.append(Balloon("red"))
party.append(Balloon("blue"))
print("balloons at the party:", len(party))
print("end of main")

Output:

pop! red balloon is gone
pop! blue balloon is gone
balloons at the party: 2
end of main

Each new Balloon is created and handed straight to the list, so the list is the owner. Nobody else holds them. Then look closely at the order: the balloons pop before the count is printed. len(party) is the list’s last use. Mojo gets the length (2), destroys the list and its balloons, and only then runs print with the number it already has. ASAP destruction really is as soon as possible.

Rule 3 says a reference keeps the value alive. Here r is a reference to a field of n, a second name for the same text. (ref bindings are covered in Mojo References & Origins.)

@fieldwise_init
struct Noisy(Movable):
var name: String
def __deinit__(deinit self):
print("destroyed", self.name)
def main():
var n = Noisy("box")
ref r = n.name
print("made a reference")
print("the reference says", r)
print("end")

Output:

made a reference
the reference says box
destroyed box
end

The last line that mentions n itself is ref r = n.name, but n isn’t destroyed there. Mojo sees that r still points into n, so it keeps n alive until r’s last use. A reference can never point at something that’s already gone.

You don’t need this to write Mojo, but it helps to know where values live. Small, fixed-size values like an Int live on the stack, a fast area that’s cleaned up automatically when a function returns. Values that can grow, like the text in a String or the items in a List, live on the heap, a big area where memory has to be requested and given back.

The owner is what gives heap memory back. When a List is destroyed, its destructor frees the heap memory holding the items. Because every value has one owner and Mojo knows exactly when that owner is done, the memory is freed once, at the right time, without a garbage collector running in the background. The intro to value ownership in the manual explains the stack and heap in more detail.

Python Mojo
Who frees memory The garbage collector The value’s owner, at its last use
When an object is freed When nobody refers to it any more (usually soon, not guaranteed) Right after its last use, decided at compile time
Several names for one list Normal (b = a) Only through explicit references or ArcPointer
Passing to a function The function shares the object The function borrows it read-only, or takes ownership with var and ^

Read this program and write down the order of the printed lines before you run it.

@fieldwise_init
struct Tag(Movable):
var label: String
def __deinit__(deinit self):
print("removing tag", self.label)
def main():
var a = Tag("A")
var b = Tag("B")
print("tags made")
print(b.label)
print(a.label)
print("done")

Hint: each tag is removed right after the last line that uses it.

Show solution

Output:

tags made
B
removing tag B
A
removing tag A
done

Both tags are alive at tags made. b is last used on print(b.label), so it goes first. a is used one line later, so it goes after that. Neither waits for the end of main.

Write a struct Book with a title: String field and a __deinit__ that prints closing <title>. Write a function read(var book: Book) that prints reading <title>. In main, create a book called Dune, pass it to read with ^, then print back in main.

Hint: the book’s new owner is read, so it’s closed before back in main.

Show solution
@fieldwise_init
struct Book(Movable):
var title: String
def __deinit__(deinit self):
print("closing", self.title)
def read(var book: Book):
print("reading", book.title)
def main():
var b = Book("Dune")
read(b^)
print("back in main")

Output:

reading Dune
closing Dune
back in main

read owns the book after b^, so the book is destroyed inside read. main can’t use b again after handing it over.

  • Every value has one owner (usually a variable). Structs own their fields, lists own their items.
  • When the owner is done, Mojo destroys the value right after its last use (ASAP destruction), not at the end of the block.
  • A function can borrow a value (the default) or take ownership of it (a var argument plus ^ at the call).
  • ^ transfers ownership; the old variable is empty afterwards, and using it is a compile error.
  • A reference keeps its owner alive for as long as the reference is used.
  • These rules replace a garbage collector and rule out use-after-free, double frees and leaks in normal code.

Next up: argument conventions, the keywords that say whether a function borrows, changes or owns what you pass in.

Quick check

1. When does Mojo destroy a local variable's value?
2. What does keep(red^) do when keep takes a var argument?
3. You create a reference ref r = n.name, then use r later. When can n be destroyed?
4. Which bug does single ownership prevent?