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.
What ^ does
Section titled “What ^ does”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.
The old variable is empty
Section titled “The old variable is empty”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 managerThis 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]Moving into a function
Section titled “Moving into a function”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:
3For 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.
Moving out of a function
Section titled “Moving out of a function”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.
Moving into a collection
Section titled “Moving into a collection”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.
Moving out of a struct field
Section titled “Moving out of a struct field”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_initstruct 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.
Mojo moves at the last use
Section titled “Mojo moves at the last use”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: aThe 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.
Move-only and immovable types
Section titled “Move-only and immovable types”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_initstruct 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 moduleYou’ll rarely write one yourself; they matter for things like locks, where other code keeps a pointer to the value.
Draining a list with for var x in items^
Section titled “Draining a list with for var x in items^”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.
Practice
Section titled “Practice”1. Fix the returns
Section titled “1. Fix the returns”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.
2. Move or copy?
Section titled “2. Move or copy?”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 ofxto a new owner without copying it.- After a move,
xis uninitialized; using it is a compile error, until you assign a new value. - Use
^to pass a value to avarargument, 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 Movabletypes 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Transfer arguments (
varand^): the manual’s section on the transfer sigil andvararguments. - Creating values: move initializers, move-only and immovable types.
- Mojo ownership cheat sheet: what each assignment, call and return does with ownership.
- Movable trait: the standard library reference for types that can be moved.