Skip to content

Mojo References & Origins

A reference is a second name for a value that someone else owns. It lets you read or change that value without copying it. References are where memory bugs usually hide in other languages: a reference that points at something already freed, or at a list that moved its items somewhere else. Mojo checks every reference at compile time, and the tool it uses for that is called an origin. This page shows references first, then what origins are and when you’ll write them yourself.

You create a reference with ref instead of var:

def main():
var city = String("Oslo")
ref r = city
r += " center"
print(city)
var c = city
c += "!"
print(city, "/", c)

Output:

Oslo center
Oslo center / Oslo center!
  • ref r = city makes r another name for the same string. Changing r changes city.
  • var c = city makes a copy. Changing c leaves city alone.

That’s the whole difference: var means “I own my own value”, ref means “I’m looking at someone else’s”. A ref doesn’t own anything, so it never destroys anything either.

References into a list work the same way:

def main():
var nums: List[Int] = [1, 2, 3]
ref first = nums[0]
first += 10
print(first)
nums.append(4)
print(nums)

Output:

11
[11, 2, 3, 4]

You’ve used references before without the word: for ref s in scores in a loop, and every default (read-only) function argument is a reference too.

Now a small change: use first after appending to the list.

def main():
var nums: List[Int] = [1, 2, 3]
ref first = nums[0]
nums.append(4)
print(first)
hello.mojo:5:11: error: use of invalidated interior reference 'nums["element"]'
print(first)
^
hello.mojo:4:16: note: origin was invalidated here
nums.append(4)
^
mojo: error: failed to run the pass manager

Why is this a problem? A list keeps its items in a block of memory. When the block is full, append gets a bigger block, moves the items over and frees the old one. first would still point into the old, freed block. In C or C++ this compiles and then reads garbage, or crashes, at some random later point. Mojo refuses to build it, and the note shows exactly which line made the reference invalid.

In the previous example, first was last used before the append, so there was no problem.

The same check protects views. A slice of a list is a Span (see Mojo Span), and a slice of a string is a StringSpan. Both are references to the original data:

def main():
var text = String("Hello, world")
var hello = text[byte=0:5]
print(hello)
text += "!"
print(hello)
hello.mojo:6:10: error: use of invalidated interior reference 'text["bytes"]'
print(hello)
^
hello.mojo:5:10: note: origin was invalidated here
text += "!"
^
mojo: error: failed to run the pass manager

Changing the string might move its bytes, so the old view can’t be trusted any more. If you need the text to survive changes, make an owned copy with String(text[byte=0:5]).

Moving the owner away is caught too: if you write var moved = nums^ while a reference into nums is still used later, Mojo says use of uninitialized value 'nums'.

To make those checks, the compiler attaches an origin to every reference. An origin answers two questions:

  1. Which variable owns the value this reference points into?
  2. Can the value be changed through this reference?

Origins exist only while compiling. They don’t take memory or time at run time. Most of the time the compiler works them out on its own, and you never see them. The manual’s page on lifetimes, origins and references describes them in full.

A function normally returns a value (a copy, or a moved value). It can also return a reference into one of its arguments. Then the return type says ref[...], and inside the brackets goes the origin: where the reference points.

def first(ref xs: List[Int]) -> ref[xs[0]] Int:
return xs[0]
def main():
var nums: List[Int] = [10, 20, 30]
ref f = first(nums)
f = 99
print(nums)
var copy = first(nums)
print(copy)

Output:

[99, 20, 30]
99

Read -> ref[xs[0]] Int as “returns a reference to an Int that lives where xs[0] lives”. Two things to notice:

  • ref xs takes the list as a ref argument, so the returned reference is mutable when the caller’s list is mutable, as it is here. (That’s the ref convention from Mojo Argument Conventions.)
  • How you catch the result matters. ref f = first(nums) keeps the reference, so f = 99 changes the list. var copy = first(nums) copies the number out.

The origin has to match what you actually return. Writing -> ref[xs] Int (a reference into the list itself, not into an element) is rejected:

def first(ref xs: List[Int]) -> ref[xs] Int:
return xs[0]
def main():
var nums: List[Int] = [10, 20, 30]
print(first(nums))
hello.mojo:2:14: error: cannot return reference with incompatible origin: 'origin_of(xs["element"])' vs 'origin_of(xs)'
return xs[0]
^
mojo: error: failed to parse the provided Mojo source module

Mojo tracks a list’s elements separately from the list, because, as you saw, appending can move the elements while the list itself stays put.

Sometimes a function returns a reference into one argument or another. Then you list both in the origin. Mojo keeps both owners alive for as long as the reference is used:

def longer(ref a: String, ref b: String) -> ref[a, b] String:
if a.byte_length() >= b.byte_length():
return a
return b
def main():
var x = String("apple")
var y = String("kiwi")
ref winner = longer(x, y)
print(winner)

Output:

apple

ref[a, b] is called an origin union. If you wrote only ref[a], returning b would be the same “incompatible origin” error, because the compiler wouldn’t know the result might point into b. The returned reference is mutable only if both a and b are mutable.

You won’t write origins often, but you’ll read them in the docs and in error messages:

  • origin_of(x) gives the origin of a value. ref[xs] is short for ref[origin_of(xs)].
  • Span[T, origin] and StringSpan[origin]: views carry the origin of the data they look at. That’s how the string example above was caught.
  • Pointer[T, origin]: a safe pointer carries an origin too, as you’ll see in Mojo Pointers.
  • MutUntrackedOrigin: memory the compiler does not track, used for raw allocations. That’s the territory of Mojo Unsafe Pointers.

Python has no references in this sense, because every name already refers to a shared object. The bugs origins prevent mostly can’t happen in Python either: Python keeps an object alive as long as anything refers to it, at the cost of a garbage collector. Mojo gets the same safety by checking at compile time, so there’s no run-time cost. The price is that some code that would be fine in Python (like holding a reference across an append) has to be written differently.

This program should print apple and then [apple, kiwi, plum]. It doesn’t compile. Fix it by moving one line.

def main():
var fruits: List[String] = ["apple", "kiwi"]
ref top = fruits[0]
fruits.append("plum")
print(top)
print(fruits)

Hint: a reference into a list must not be used after the list grows.

Show solution
def main():
var fruits: List[String] = ["apple", "kiwi"]
ref top = fruits[0]
print(top)
fruits.append("plum")
print(fruits)

Output:

apple
[apple, kiwi, plum]

top’s last use is now before the append, so it can’t point into memory that was moved. Another fix is var top = fruits[0].copy(), an owned copy that doesn’t care what happens to the list.

Write def last(ref xs: List[Int]) -> ref[xs[0]] Int that returns a reference to the last item. In main, use it to set the last item of [1, 2, 3] to 30 and print the list.

Hint: the last index is len(xs) - 1. All elements share the same origin, so xs[0] works in the return type even for another index.

Show solution
def last(ref xs: List[Int]) -> ref[xs[0]] Int:
return xs[len(xs) - 1]
def main():
var nums: List[Int] = [1, 2, 3]
last(nums) = 30
print(nums)

Output:

[1, 2, 30]

Assigning to last(nums) writes through the reference into the list. The origin xs[0] stands for “the list’s elements”, not only the first one.

  • ref name = value makes a second name with no copy; var makes an owned copy.
  • Mojo checks at compile time that a reference is never used after its value is invalidated: by an append, a change to a string, or a move.
  • An origin tells the compiler who owns the referenced value and whether it can change.
  • Origins are inferred for local references and arguments; you write them on ref return types, like -> ref[xs[0]] Int.
  • ref[a, b] is an origin union for a reference that might point into either argument.
  • Span, StringSpan and Pointer all carry an origin to stay safe.

Next up: the value lifecycle, how values are created, copied, moved and destroyed, and how your own structs control each step.

Quick check

1. What is the difference between ref r = city and var c = city for a String?
2. Why does Mojo reject using ref first = nums[0] after nums.append(4)?
3. Where do you usually have to write an origin yourself?
4. What does -> ref[a, b] String mean?