Skip to content

Mojo Pointers

A pointer is a value that holds a memory address: the place where some other value lives. Instead of carrying the value around, you carry its address, and you follow the address when you need the value. Python never shows you pointers (every Python name is secretly one), but in Mojo you’ll meet them when you build data structures, share one value between several owners or talk to C code. This page covers the three safe pointer types. The unsafe side, where you manage raw memory yourself, comes in the next lesson.

Pointer(to=value) makes a pointer to a value you already have. To get at the value, write [] after the pointer. That’s called dereferencing:

def main():
var count = 0
var ptr = Pointer(to=count)
ptr[] = 100
ptr[] += 10
print(ptr[])
print(count)

Output:

110
110

ptr doesn’t hold a copy of count. It holds the address of count, so writing through ptr[] changes count itself. Pointer is always available; you don’t need an import.

The value a pointer points to is called the pointee. For a struct, you reach its fields through the pointee:

@fieldwise_init
struct Point(Movable):
var x: Int
var y: Int
def main():
var p = Point(1, 2)
var ptr = Pointer(to=p)
ptr[].x = 10
print(p.x, ptr[].y)

Output:

10 2

A Pointer made with to= carries the origin of the value it points to. So the same rules as for references apply: the value can’t disappear while the pointer is still used.

def main():
var nums: List[Int] = [1, 2, 3]
var p = Pointer(to=nums)
var moved = nums^
print(p[])
hello.mojo:5:12: error: use of uninitialized value 'nums'
print(p[])
^
hello.mojo:2:9: note: 'nums' declared here
var nums: List[Int] = [1, 2, 3]
^
mojo: error: failed to run the pass manager

nums was moved away, so the pointer would point at nothing. Mojo won’t compile it. This is what makes Pointer(to=...) safe: as long as you only create pointers this way and use [], the pointer is exactly as safe as the value it points to. The manual’s intro to pointers calls these the safe uses of Pointer.

A function can take a pointer as an argument. The type spells out what it accepts:

def add_one(p: Pointer[mut=True, Int, _]):
p[] += 1
def main():
var n = 1
add_one(Pointer(to=n))
print(n)

Output:

2

Pointer[mut=True, Int, _] means “a pointer to an Int that may be changed, from any origin”. The _ lets Mojo fill in the origin from whatever you pass. For an argument like this, mut n: Int would be simpler and does the same job. Pointers earn their place when the address has to be kept: in a struct field, in a collection, or handed to C code.

OwnedPointer: one owner, value on the heap

Section titled “OwnedPointer: one owner, value on the heap”

OwnedPointer puts a value in its own piece of heap memory and owns it. When the OwnedPointer is destroyed, so is the value inside. It has to be imported from std.memory:

from std.memory import OwnedPointer
@fieldwise_init
struct Photo(Movable):
var name: String
def __deinit__(deinit self):
print("photo", self.name, "destroyed")
def show(p: OwnedPointer[Photo]):
print("showing", p[].name)
def main():
var box = OwnedPointer(Photo("beach"))
show(box)
var moved = box^
print("moved the box")
show(moved)
print("end of main")

Output:

showing beach
moved the box
showing beach
photo beach destroyed
end of main

OwnedPointer follows the ownership rules from Mojo Ownership: one owner at a time. You can move it with ^ (the photo stays where it is on the heap; only the pointer changes hands), but you can’t copy it:

from std.memory import OwnedPointer
def main():
var box = OwnedPointer(42)
var other = box
hello.mojo:5:17: error: value of type 'OwnedPointer[Int]' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable'
var other = box
^~~
hello.mojo:5:17: note: consider transferring the value with '^'
mojo: error: failed to parse the provided Mojo source module

A copy would mean two owners of one photo, and then it would be destroyed twice. Why would you put a value behind an OwnedPointer at all? Mostly for structs that need to refer to another value of their own type, like a node in a tree. A struct can’t contain itself directly (it would be infinitely big), but it can contain a pointer to another one. The manual’s page on self-referential structs shows how.

Sometimes you really want several owners of one value, the way Python works. That’s ArcPointer. Copying an ArcPointer doesn’t copy the value; it adds another owner. The value is destroyed when the last owner is gone:

from std.memory import ArcPointer
@fieldwise_init
struct Scoreboard(Movable):
var points: Int
def __deinit__(deinit self):
print("scoreboard freed")
def main():
var home = ArcPointer(Scoreboard(0))
var away = home
print("owners:", home.count())
away[].points += 3
home[].points += 1
print("points:", home[].points)
print("end of main")

Output:

owners: 2
points: 4
scoreboard freed
end of main

var away = home copies the pointer, not the scoreboard. Both names reach the same scoreboard, so the += 3 through away and the += 1 through home add up to 4. count() tells you how many owners there are right now. “Arc” stands for atomic reference counting: every ArcPointer copy adds one to a shared count, and every destroyed one takes one away. At zero, the value is freed.

In many languages a pointer can be null, meaning it points to nothing, and following a null pointer crashes your program. None of Mojo’s pointer types can be null. When you need “maybe a pointer”, wrap it in Optional (from Mojo Optional):

from std.memory import OwnedPointer
def main():
var maybe: Optional[OwnedPointer[Int]] = None
if not maybe:
print("nothing yet")
maybe = OwnedPointer(7)
if maybe:
print("got", maybe.value()[])

Output:

nothing yet
got 7

Now “no pointer” is a case the type system knows about, so you have to check for it before using the value.

Pointer(to=x) OwnedPointer ArcPointer
Owns the value No, x does Yes, alone Yes, shared
Allocates memory No Yes, on creation Yes, on creation
Can be copied Yes (copies the address) No, only moved Yes (adds an owner)
Value destroyed when x is destroyed the pointer is destroyed the last copy is destroyed
Import none from std.memory import OwnedPointer from std.memory import ArcPointer

Pointer can do more: it can also point to raw memory you allocate yourself. Those operations all start with unsafe_, and they’re the topic of the next lesson.

Every Python variable is a pointer to an object, and the objects are reference counted, so Python behaves a lot like “ArcPointer everywhere”. Mojo makes you pick: most values have one owner and no pointer at all, and you use a pointer type only when you need what it offers.

Create var temperature = 20. Make a pointer to it, use the pointer to add 5, then print temperature.

Hint: Pointer(to=...) and ptr[] += ....

Show solution
def main():
var temperature = 20
var ptr = Pointer(to=temperature)
ptr[] += 5
print(temperature)

Output:

25

The pointer holds the address of temperature, so changing ptr[] changes temperature.

Make an ArcPointer holding a List[String] (create the list first, then pass it in with ^). Copy the pointer into a second variable. Append "milk" through the first and "eggs" through the second, then print the list and the number of owners.

Hint: ArcPointer(items^), then a[].append(...).

Show solution
from std.memory import ArcPointer
def main():
var items = List[String]()
var mine = ArcPointer(items^)
var yours = mine
mine[].append("milk")
yours[].append("eggs")
print(mine[])
print("owners:", mine.count())

Output:

[milk, eggs]
owners: 1

Both pointers reach the same list, so it holds both items. The owner count is 1, not 2: yours was last used on the append line, so it was already destroyed by the time count() ran. That’s ASAP destruction again.

  • A pointer holds the address of a value; ptr[] follows it (dereferencing).
  • Pointer(to=x) points to an existing value, carries its origin, and is checked like a reference.
  • OwnedPointer owns one value on the heap; it can be moved but not copied.
  • ArcPointer gives shared ownership with a reference count; the value is freed when the last copy goes.
  • Mojo pointers are never null: use Optional[...] for “maybe a pointer”.
  • OwnedPointer and ArcPointer need from std.memory import ...; Pointer doesn’t.

Next up: unsafe pointers, allocating and freeing memory yourself, and what can go wrong.

Quick check

1. What does ptr[] = 5 do when ptr = Pointer(to=n)?
2. Why can't you write var other = box when box is an OwnedPointer?
3. When is the value inside an ArcPointer destroyed?
4. How do you represent a pointer that might point to nothing?