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
ImplicitlyCopyableis what lets a plain=duplicate the struct.duplicategets its ownpointsandlabelto overwrite.originalprints unchanged, proving the two never shared storage.
Keywords and builtins used here
IntMovableStringdefmainprintstructvar
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.
Step 1 of 5 in Value semantics, step 6 of 22 in Structs & traits.