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 three rules
Section titled “The three rules”The Mojo manual’s ownership page sums it up like this:
- Every value has exactly one owner at a time. Usually the owner is a variable.
- When the owner’s life ends, Mojo destroys the value.
- 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.
Watching a value get destroyed
Section titled “Watching a value get destroyed”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_initstruct 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 balloonpop! red balloon is goneI have a blue balloonpop! blue balloon is goneend of mainred 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.
Lending a value
Section titled “Lending a value”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_initstruct 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 balloonback in main, still minenow I own the red balloonpop! red balloon is goneend of mainTwo different things happen here:
look_at(red)lends the balloon.look_atcan read it, butmainstill owns it. Whenlook_atreturns, nothing is destroyed.keep(red^)gives the balloon away. Thevarin front of the argument means “this function wants to own it”, and the^afterredmeans “I’m handing it over”. Nowkeepis the owner, so the balloon pops whenkeepis done with it, beforemainprints 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.
Giving a value away
Section titled “Giving a value away”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_initstruct 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 ^.
Owners own what’s inside them
Section titled “Owners own what’s inside them”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_initstruct 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 gonepop! blue balloon is goneballoons at the party: 2end of mainEach 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.
References keep the owner alive
Section titled “References keep the owner alive”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_initstruct 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 referencethe reference says boxdestroyed boxendThe 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.
Stack, heap and why this matters
Section titled “Stack, heap and why this matters”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.
Coming from Python?
Section titled “Coming from Python?”| 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 ^ |
Practice
Section titled “Practice”1. Predict the order
Section titled “1. Predict the order”Read this program and write down the order of the printed lines before you run it.
@fieldwise_initstruct 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 madeBremoving tag BAremoving tag AdoneBoth 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.
2. Hand it over
Section titled “2. Hand it over”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_initstruct 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 Duneclosing Duneback in mainread 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
varargument 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Ownership: the Mojo manual’s page on the ownership rules and argument conventions.
- Intro to value ownership: stack, heap and why Mojo chose ownership over garbage collection.
- Automatic destruction: exactly when Mojo destroys values, with a step-by-step example.
- Mojo ownership cheat sheet: owners, references, transfers and lifecycle methods on one page.