Mutating with mut in Mojo
mut marks an argument the callee may change in place, edits landing on the caller's value.
@fieldwise_init
struct Basket(ImplicitlyCopyable, Movable):
var count: Int
def take(mut self, n: Int):
self.count -= n
def refill(mut basket: Basket, n: Int):
basket.count += n
def main():
var basket = Basket(2)
refill(basket, 5)
basket.take(1)
print(basket.count)
How it works
take(mut self, n: Int)lets a method write back to its own fields.refill(mut basket: Basket, n: Int)mutates a struct owned bymain.- Both edits stack up, so
basket.countprints the running total.
Keywords and builtins used here
IntMovabledefmainprintrefillselfstructtakevar
The run, in numbers
- Lines
- 17
- Characters to type
- 269
- Tokens
- 74
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 56 seconds.
Step 3 of 5 in Value semantics, step 8 of 22 in Structs & traits.