Skip to content

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.

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.

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: a
copy
copy: a -> a-copy
move
move: a
put b in a list
move: a-copy
deinit: a-copy
end of main a 1
deinit: a

Let’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 from a into c, and a becomes empty.
  • team.append(b^) moves b into the list’s memory: another move.
  • Then the destruction. len(team) is the list’s last use, so the list (and the a-copy inside it) is destroyed right there, before print even runs. c is still needed by print, 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.

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 manager

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

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

Point 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 = a copies automatically, like Int and String. Use it only for small, cheap types.

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

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.

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.

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
_ = two

Output:

copying report
copying report
done

Each .copy() runs the copy initializer once. The _ = one lines just mark the copies as used, so the compiler doesn’t warn about unused variables.

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 x
copy x2
names: x x2
deinit x2
deinit x

x 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 self and must set every field.
  • Copyable gives .copy(); ImplicitlyCopyable also allows plain var 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

1. Which signature is the copy initializer in Mojo 1.2?
2. What does out self mean in an __init__?
3. A struct only holds an Int and a String. Does it need a hand-written move initializer?
4. After var c = a^ runs the move initializer, what happens to the old value in a?