Skip to content

Mojo Moving Values

You’ve seen the little ^ a few times already: return xs^, keep(red^), var b = a^. It’s called the transfer sigil, and it moves a value to a new owner without copying it. Python has nothing like it, because Python never moves objects: it just adds another name. This page covers what ^ does, what happens to the variable you moved from, and the places where Mojo moves values without being asked.

Put ^ right after a variable name to say “give this value away”:

def main():
var a: List[Int] = [1, 2, 3]
var b = a^
print(b)

Output:

[1, 2, 3]

b now owns the list. No items were copied: the list just changed owners. The old name a is now uninitialized, which means it holds no value at all.

Because a holds nothing after the move, using it is a compile error:

def main():
var a: List[Int] = [1, 2, 3]
var b = a^
print(a)
hello.mojo:4:10: error: use of uninitialized value 'a'
print(a)
^
hello.mojo:2:9: note: 'a' declared here
var a: List[Int] = [1, 2, 3]
^
mojo: error: failed to run the pass manager

This check happens while compiling, so a moved-from variable can never be used by accident at run time. The compiler also follows every path through your code. If the move only happens inside an if, the variable might be empty afterwards, and Mojo treats that as empty too. The same goes for a move inside a loop: the second time round, there’s nothing left to move.

You can give an empty variable a new value, though, and then it’s usable again:

def main():
var names: List[String] = ["ana", "ben"]
var moved = names^
names = ["cy"]
print(names, moved)

Output:

[cy] [ana, ben]

A function that takes a var argument wants to own its value. If you pass x^, it gets the original and no copy is made:

def keep_names(var names: List[String]) -> Int:
names.append("zoe")
return len(names)
def main():
var guests: List[String] = ["ana", "ben"]
print(keep_names(guests^))

Output:

3

For a List, you have to choose: guests^ to hand it over, or guests.copy() to keep your own. Mojo won’t copy a list implicitly (Mojo Argument Conventions shows the error). For a cheap type like String, leaving out the ^ makes a copy, and adding it skips the copy.

When a function builds a list and returns it, the list moves out to the caller:

def make_list(n: Int) -> List[Int]:
var xs = List[Int]()
for i in range(n):
xs.append(i * i)
return xs^
def main():
var squares = make_list(5)
print(squares)

Output:

[0, 1, 4, 9, 16]

Without the ^, return xs is the same “cannot be implicitly copied” error, because Mojo would have to copy the list. xs is about to disappear anyway, so moving it out is free. Int and String don’t need the ^ on return.

append takes its argument as var, so the list becomes the owner of whatever you add. A brand-new value moves in automatically. A value in a variable moves in with ^:

def main():
var name = String("Ana")
var names = List[String]()
names.append(name^)
names.append("Ben")
print(names)
var last = names.pop()
print(last, names)

Output:

[Ana, Ben]
Ben [Ana]

pop() works the other way round: it moves the last item out of the list and gives it to you.

You can move a single field out of a struct, but then the struct has a hole in it. Mojo lets you do this only if you fill the hole before the struct is used again:

@fieldwise_init
struct User(Movable):
var name: String
var tags: List[String]
def main():
var u = User("ana", ["admin"])
var t = u.tags^
print(t)
u.tags = ["guest"]
print(u.name, u.tags)

Output:

[admin]
ana [guest]

If you leave out the refill and use u again, Mojo stops you. Depending on what you use, it says use of uninitialized value 'u.tags' or value 'u.tags' cannot be consumed, because 'u' is used later.

Here’s something Mojo does for you. When a value is passed to a var argument at its last use, Mojo doesn’t bother copying it: it moves it, even without ^. You can see this with a struct that prints when it’s copied. (Writing your own copy and move initializers is covered in Mojo Value Lifecycle.)

struct Tracer(ImplicitlyCopyable):
var name: String
def __init__(out self, name: String):
self.name = name
def __init__(out self, *, copy: Self):
self.name = copy.name + " (copy)"
print(" copying!")
def __init__(out self, *, deinit move: Self):
self.name = move.name^
print(" moving!")
def take(var t: Tracer):
print(" take got:", t.name)
def main():
var a = Tracer("a")
print("first call:")
take(a)
print("second call, the last use of a:")
take(a)

Output:

first call:
copying!
take got: a (copy)
second call, the last use of a:
take got: a

The first call needs a copy, because a is used again afterwards. The second call is the last use of a, so Mojo hands over the original, no copy at all. It didn’t even need the move initializer: the value just stays where it is and changes owner. The manual’s section on transfers explains that a transfer and a “move” aren’t always the same operation for exactly this reason.

Some types can be moved but never copied. OwnedPointer (from Mojo Pointers) is one: there’s only ever one owner of its value, so a copy would break the rule. A struct that’s Movable but not Copyable is move-only too.

A few types can’t even be moved, because their address in memory must never change. You mark them not Movable:

@fieldwise_init
struct Pinned(not Movable):
var n: Int
def main():
var p = Pinned(1)
var q = p^
hello.mojo:7:14: error: cannot transfer value into destination, because 'Pinned' doesn't conform to 'Movable'
var q = p^
^
mojo: error: failed to parse the provided Mojo source module

You’ll rarely write one yourself; they matter for things like locks, where other code keeps a pointer to the value.

A normal for loop borrows each item. If you want to take the items out of a list, one by one, move the list into the loop:

def main():
var words: List[String] = ["ana", "ben"]
for var w in words^:
w += "!"
print(w)

Output:

ana!
ben!

words^ hands the whole list to the loop, and for var w makes each item a value the loop body owns. After the loop, words is empty.

This function should build a shopping list and return it, but it doesn’t compile. Fix it.

def shopping() -> List[String]:
var items = List[String]()
items.append("milk")
items.append("eggs")
return items
def main():
print(shopping())

Hint: the error says the list “cannot be implicitly copied” and suggests a fix.

Show solution
def shopping() -> List[String]:
var items = List[String]()
items.append("milk")
items.append("eggs")
return items^
def main():
print(shopping())

Output:

[milk, eggs]

items is about to disappear at the end of the function, so moving it out with ^ costs nothing.

You have var team: List[String] = ["ana", "ben"]. Add it to a List[List[String]] called teams, and then print both teams and team. Then change the program so that team is moved instead, and see what the compiler says about the last print.

Hint: append takes ownership. Only .copy() lets you keep using team.

Show solution
def main():
var team: List[String] = ["ana", "ben"]
var teams = List[List[String]]()
teams.append(team.copy())
print(teams)
print(team)

Output:

[[ana, ben]]
[ana, ben]

With teams.append(team^) instead, print(team) gives “use of uninitialized value ‘team’”, because the list now belongs to teams.

  • x^ transfers the value of x to a new owner without copying it.
  • After a move, x is uninitialized; using it is a compile error, until you assign a new value.
  • Use ^ to pass a value to a var argument, to return a list (return xs^) and to add it to a collection.
  • You can move a field out of a struct if you refill it before the struct is used again.
  • At a value’s last use, Mojo moves it for you instead of copying.
  • Move-only types (like OwnedPointer) can’t be copied; not Movable types can’t even be moved.

Next up: references and origins, how Mojo checks that a reference never outlives the value it points to.

Quick check

1. After var b = a^, what can you do with a?
2. Why does return xs fail for a local List[Int] but return xs^ works?
3. A String variable is passed to a var argument for the last time, without ^. What does Mojo do?
4. What does for var w in words^: do?