typestar

Assignment copies the value in Mojo

Mojo structs are values, so assigning one makes an independent copy, not an alias.

@fieldwise_init
struct Score(ImplicitlyCopyable, Movable):
    var points: Int
    var label: String


def main():
    var original = Score(10, "first")
    var duplicate = original
    duplicate.points = 99
    duplicate.label = "second"
    print(original.points, original.label)
    print(duplicate.points, duplicate.label)

How it works

  1. ImplicitlyCopyable is what lets a plain = duplicate the struct.
  2. duplicate gets its own points and label to overwrite.
  3. original prints unchanged, proving the two never shared storage.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
294
Tokens
66
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 1 of 5 in Value semantics, step 6 of 22 in Structs & traits.

← Previous Next →