typestar

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

  1. take(mut self, n: Int) lets a method write back to its own fields.
  2. refill(mut basket: Basket, n: Int) mutates a struct owned by main.
  3. Both edits stack up, so basket.count prints the running total.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Value semantics, step 8 of 22 in Structs & traits.

← Previous Next →