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.
A reference is a second name
Section titled “A reference is a second name”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 centerOslo center / Oslo center!ref r = citymakesranother name for the same string. Changingrchangescity.var c = citymakes a copy. Changingcleavescityalone.
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.
The danger Mojo protects you from
Section titled “The danger Mojo protects you from”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 managerWhy 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 managerChanging 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'.
What an origin is
Section titled “What an origin is”To make those checks, the compiler attaches an origin to every reference. An origin answers two questions:
- Which variable owns the value this reference points into?
- 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.
Returning a reference
Section titled “Returning a reference”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]99Read -> ref[xs[0]] Int as “returns a reference to an Int that lives where xs[0] lives”. Two things to notice:
ref xstakes the list as arefargument, so the returned reference is mutable when the caller’s list is mutable, as it is here. (That’s therefconvention from Mojo Argument Conventions.)- How you catch the result matters.
ref f = first(nums)keeps the reference, sof = 99changes 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 moduleMojo tracks a list’s elements separately from the list, because, as you saw, appending can move the elements while the list itself stays put.
A reference into one of two values
Section titled “A reference into one of two values”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:
appleref[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.
Where else you’ll see origins
Section titled “Where else you’ll see origins”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 forref[origin_of(xs)].Span[T, origin]andStringSpan[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.
Coming from Python?
Section titled “Coming from Python?”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.
Practice
Section titled “Practice”1. Fix the reference
Section titled “1. Fix the reference”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.
2. Return a reference
Section titled “2. Return a reference”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 = valuemakes a second name with no copy;varmakes 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
refreturn types, like-> ref[xs[0]] Int. ref[a, b]is an origin union for a reference that might point into either argument.Span,StringSpanandPointerall 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Lifetimes, origins, and references: the manual’s full page on origins,
refarguments andrefreturn values. - Ownership: variables, references and the ownership rules origins enforce.
- Mojo ownership cheat sheet:
varversusref, views and origins on one page. - Origin: the standard library reference for the origin type.