Mojo Error: expression must be mutable
error: expression must be mutable in assignment and error: expression must be mutable for in-place operator destination mean you tried to change something you’re only allowed to read. The first comes from =, the second from +=, -=, *= and friends. In Mojo, function arguments, self in a plain method and loop variables are read-only unless you say otherwise. For the other errors in this series, see Mojo Errors Explained.
The error message
Section titled “The error message”def add_one(n: Int): n += 1
def main(): var x = 1 add_one(x) print(x)counter.mojo:2:5: error: expression must be mutable for in-place operator destination n += 1 ^mojo: error: failed to parse the provided Mojo source moduleMutable means “can be changed”. In-place operator destination is the thing on the left of +=, the value that would be changed. Here that’s n, a function argument, and arguments are read-only by default.
What it means
Section titled “What it means”When you call add_one(x), Mojo doesn’t copy x. It hands the function a read-only reference to it: the function can look at x under the name n, but can’t change it. That’s Mojo’s default argument convention. It’s cheap (no copy) and safe (the caller’s value can’t change behind its back).
The same rule applies in three more places:
| Where | Read-only by default | How to make it changeable |
|---|---|---|
| A function argument | def f(n: Int) |
def f(mut n: Int) |
self in a method |
def bump(self) |
def bump(mut self) |
A for loop variable |
for n in nums: |
for ref n in nums: |
A comptime constant |
comptime LIMIT = 3 |
use var instead, if it has to change |
In Python, assigning to an argument just rebinds a local name, and n += 1 on an int never changed the caller’s number anyway. Mojo makes you say which of the two you want. The ownership page of the Mojo manual explains the argument conventions.
How to fix it
Section titled “How to fix it”Fix 1: Mark the argument mut
Section titled “Fix 1: Mark the argument mut”If the function is supposed to change the caller’s variable, say so with mut:
def add_one(mut n: Int): n += 1
def main(): var x = 1 add_one(x) print(x)Output:
2Now n is a mutable reference to x, so n += 1 changes x. The caller has to pass a variable, though: add_one(5) fails with value passed to mutable argument 'n' must be mutable, because there’s nothing to change in a literal.
This is the same fix for lists. A function that calls items.append(...) on a read-only argument gets a slightly different message, invalid use of mutating method on rvalue of type 'List[String]'. The fix is mut items: List[String].
Fix 2: Use mut self in methods that change the struct
Section titled “Fix 2: Use mut self in methods that change the struct”A method that changes a field needs mut self:
struct Counter: var count: Int
def __init__(out self): self.count = 0
def bump(mut self): self.count += 1
def main(): var c = Counter() c.bump() c.bump() print(c.count)Output:
2With plain self, self.count += 1 gives expression must be mutable for in-place operator destination, pointing at self.count. Methods that only read fields keep plain self. See Mojo Methods.
Fix 3: Use for ref to change items in a loop
Section titled “Fix 3: Use for ref to change items in a loop”A loop variable is a read-only view of each item. To change the items in place, loop with ref:
def main(): var nums: List[Int] = [1, 2, 3] for ref n in nums: n *= 10 print(nums)Output:
[10, 20, 30]With plain for n in nums:, n *= 10 is this error, and n = 0 gives the in assignment version. If you want a changeable copy that doesn’t touch the list, use for var n in nums:. See Mojo For Loops.
Fix 4: Return a new value instead
Section titled “Fix 4: Return a new value instead”Sometimes changing the argument wasn’t the best idea in the first place. A function that computes something can just return it:
def plus_one(n: Int) -> Int: return n + 1
def main(): var x = 1 x = plus_one(x) print(x)Output:
2This is often easier to read than mut, especially for numbers and strings: the caller sees right there that x changes. Use mut when the value is big (like a list you’re filling) or when a function changes several things at once. Mojo Return Values has more on this style.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- A helper that “updates” its argument:
n += 1,total = ...,items.append(...). Addmut, or return the new value. - A method that changes
self.somethingwithoutmut self. - A loop that tries to change the list:
for x in xs: x += 1. Usefor ref x in xs:. - Changing a
comptimeconstant:LIMIT = 4givesexpression must be mutable in assignment. Acomptimevalue is fixed when the program is built; usevarfor values that change. See Mojo Constants.
Related errors
Section titled “Related errors”- implicit declaration of ‘x’ is not allowed: assigning to a name that doesn’t exist yet.
- value of type ‘X’ cannot be implicitly copied: the other error you meet when passing lists around.
- cannot call function that may raise: another case where the function’s signature has to say what it does.
- All Mojo error pages: the full list.
Practice
Section titled “Practice”1. A shopping list helper
Section titled “1. A shopping list helper”Make add_item add the item to the caller’s list, so the program prints [milk, bread].
def add_item(items: List[String], item: String): items.append(item)
def main(): var shopping: List[String] = [] add_item(shopping, "milk") add_item(shopping, "bread") print(shopping)Hint: which argument does the function change?
Show solution
def add_item(mut items: List[String], item: String): items.append(item)
def main(): var shopping: List[String] = [] add_item(shopping, "milk") add_item(shopping, "bread") print(shopping)Output:
[milk, bread]items is changed, so it needs mut. item is only read, so it stays as it is. Without mut, the error is invalid use of mutating method on rvalue of type 'List[String]'.
- Arguments,
self, loop variables andcomptimeconstants are read-only by default. in assignmentcomes from=;for in-place operator destinationcomes from+=and friends.- Use
mut n: Intfor an argument the function should change, andmut selffor methods that change fields. - Use
for ref x in xs:to change list items in a loop. - Often it’s clearer to return a new value instead.
Next up: cannot call function that may raise in a context that cannot raise, the error for functions that can fail.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Ownership in the Mojo manual: the read-only,
mut,varandrefargument conventions. - Mojo structs in the manual: methods with
selfandmut self. - Mojo ownership cheat sheet: which convention to pick, on one page.
- Mojo Argument Conventions: our lesson on
mut,var,refandout.