Mojo Value Lifecycle
Every value in Mojo has a life: it’s created, it may be copied or moved a few times, and in the end it’s destroyed. For each stage there’s a special method on the type, called a lifecycle method. Mojo writes most of them for you, but you can write your own to see or control what happens. This page builds a struct that prints a message at every stage, so you can watch a value’s life from start to finish.
The four lifecycle methods
Section titled “The four lifecycle methods”| Stage | Method | Runs when |
|---|---|---|
| Create | def __init__(out self, ...) |
you call Type(...) |
| Copy | def __init__(out self, *, copy: Self) |
you call .copy(), or an implicit copy happens |
| Move | def __init__(out self, *, deinit move: Self) |
a value moves to a new place in memory |
| Destroy | def __deinit__(deinit self) |
right after the value’s last use |
Copy and move are both written as __init__, because they create a new value. The keyword argument (copy or move) tells Mojo which one is which.
Watching every stage
Section titled “Watching every stage”Here’s a struct with all four methods, each printing a message:
struct Tracer(Copyable): var name: String
def __init__(out self, name: String): self.name = name print(" init:", self.name)
def __init__(out self, *, copy: Self): self.name = copy.name + "-copy" print(" copy:", copy.name, "->", self.name)
def __init__(out self, *, deinit move: Self): self.name = move.name^ print(" move:", self.name)
def __deinit__(deinit self): print(" deinit:", self.name)
def main(): print("create") var a = Tracer("a") print("copy") var b = Tracer(copy=a) print("move") var c = a^ print("put b in a list") var team = List[Tracer]() team.append(b^) print("end of main", c.name, len(team))Output:
create init: acopy copy: a -> a-copymove move: aput b in a list move: a-copy deinit: a-copyend of main a 1 deinit: aLet’s walk through it:
Tracer("a")runs__init__. That’s creation.Tracer(copy=a)runs the copy initializer..copy()does exactly the same; it’s just shorter.var c = a^runs the move initializer. The value moves fromaintoc, andabecomes empty.team.append(b^)movesbinto the list’s memory: another move.- Then the destruction.
len(team)is the list’s last use, so the list (and thea-copyinside it) is destroyed right there, beforeprinteven runs.cis still needed byprint, so it goes last.
Notice that each value is destroyed exactly once. The moved-from variables (a after a^, b after b^) are never destroyed, because there’s nothing left in them.
Creating: __init__ with out self
Section titled “Creating: __init__ with out self”An initializer has out self: self starts empty, and the initializer must fill in every field before it finishes. Forget one, and Mojo tells you:
struct Person: var name: String var age: Int
def __init__(out self, name: String): self.name = name
def main(): var p = Person("Ana")hello.mojo:5:9: error: 'self.age' is uninitialized at the implicit return from this function def __init__(out self, name: String): ^mojo: error: failed to run the pass managerYou can have several __init__ methods with different arguments (that’s overloading), and @fieldwise_init writes the simple one for you. Both are covered in Mojo Structs.
Copying: the copy initializer
Section titled “Copying: the copy initializer”The copy initializer gets the original as copy (a read-only reference) and builds the new value from it. You get one only if the struct conforms to Copyable. If you don’t write it, Mojo writes one that copies every field:
@fieldwise_initstruct Point(Copyable): var x: Int var y: Int
def main(): var p = Point(1, 2) var q = p.copy() var r = p^ q.x = 10 print(q.x, r.x)Output:
10 1Point has no lifecycle methods written by hand, but .copy() and ^ both work. Write your own copy initializer only when a plain field-by-field copy isn’t right: for example, when a field is a raw pointer and the copy needs its own fresh memory. You’ll see that in Mojo Unsafe Pointers.
There are two levels of “copyable”, and they’re traits you list after the struct name (see Mojo Common Traits):
Copyable: copies are allowed but must be written out (.copy()). Use this for anything that might be expensive.ImplicitlyCopyable:var b = acopies automatically, likeIntandString. Use it only for small, cheap types.
Moving: the move initializer
Section titled “Moving: the move initializer”The move initializer gets the old value as deinit move. The deinit convention means “this value is ending here”, so you’re allowed to take its fields with ^, as self.name = move.name^ does above. After the move initializer runs, the old value is gone, and its destructor does not run.
Every struct can be moved unless it says otherwise, and Mojo writes the move initializer for you. You’ll almost never write one by hand. And Mojo often skips the move entirely: when it can just let the value stay where it is and change its owner, it does. That’s why passing x^ to a function, or passing a value at its last use, often prints no “move” line at all. (Mojo Moving Values shows this with the same kind of tracer.)
Destroying: __deinit__
Section titled “Destroying: __deinit__”The last stage is the destructor, __deinit__(deinit self). Mojo calls it right after a value’s last use, and after it finishes, each field is destroyed in turn. If your struct only holds normal values (numbers, strings, lists), you don’t need one: Mojo destroys the fields for you. Destructors get their own lesson next, Mojo Destructors.
What Mojo writes for you
Section titled “What Mojo writes for you”For most structs you write no lifecycle methods except __init__, and often not even that:
| You write | Mojo gives you |
|---|---|
@fieldwise_init struct P: |
an __init__ taking every field, a move initializer, a destructor |
struct P(Copyable): |
also a copy initializer that copies every field |
struct P(ImplicitlyCopyable): |
also plain var b = a copies |
struct P(not Movable): |
no move: p^ into another variable is an error |
Write your own lifecycle methods when your struct manages something by hand: raw memory, a file, a connection, or something you want to count or log. The manual’s page on creating values covers the copy and move initializers in more depth.
Practice
Section titled “Practice”1. Count the copies
Section titled “1. Count the copies”Write a struct Doc(Copyable) with a title: String field and a copy initializer that prints copying <title>. In main, create one Doc, make two copies of it with .copy(), and print done.
Hint: inside the copy initializer, the original is called copy, so its title is copy.title.
Show solution
struct Doc(Copyable): var title: String
def __init__(out self, title: String): self.title = title
def __init__(out self, *, copy: Self): self.title = copy.title print("copying", copy.title)
def main(): var report = Doc("report") var one = report.copy() var two = report.copy() print("done") _ = one _ = twoOutput:
copying reportcopying reportdoneEach .copy() runs the copy initializer once. The _ = one lines just mark the copies as used, so the compiler doesn’t warn about unused variables.
2. Predict the output
Section titled “2. Predict the output”Without running it, write down what this program prints. Then run it to check.
struct Tracer(Copyable): var name: String
def __init__(out self, name: String): self.name = name print("init", self.name)
def __init__(out self, *, copy: Self): self.name = copy.name + "2" print("copy", self.name)
def __deinit__(deinit self): print("deinit", self.name)
def main(): var x = Tracer("x") var y = x.copy() print("names:", x.name, y.name)Hint: both values are last used in the same print, so neither can be destroyed before that line has finished.
Show solution
Output:
init xcopy x2names: x x2deinit x2deinit xx is created, then copied into y (named x2). Both are used by the print, so both are destroyed after it. Here the copy happens to go first. When two values have the same last use, don’t write code that depends on which one is destroyed first.
- A value is created (
__init__), maybe copied or moved, and finally destroyed (__deinit__). - The copy initializer is
__init__(out self, *, copy: Self); the move initializer is__init__(out self, *, deinit move: Self). - An initializer has
out selfand must set every field. Copyablegives.copy();ImplicitlyCopyablealso allows plainvar b = a.- Mojo writes the copy, move and destroy methods for you; write your own only for structs that manage something by hand.
- Copy, move and destroy can’t raise, and every value is destroyed exactly once.
Next up: destructors, how __deinit__ works, when it runs and how to keep a value alive a bit longer.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Value lifecycles: the manual’s overview of how values are created, initialized and destroyed.
- Creating values: initializers, copy and move initializers, move-only and immovable types.
- Initialization state: what
out selfmeans for fields and whenselfcounts as ready to use. - Struct declarations reference: the exact rules for lifecycle methods and conformances.