typestar

Read-only by default in Mojo

Arguments are read-only unless you say otherwise, which costs nothing at runtime.

@fieldwise_init
struct Recipe(ImplicitlyCopyable, Movable):
    var title: String
    var servings: Int


def scaled(recipe: Recipe, factor: Int) -> Int:
    return recipe.servings * factor


def main():
    var chili = Recipe("Chili", 4)
    print(scaled(chili, 3))
    print(chili.title, chili.servings)

How it works

  1. scaled(recipe: Recipe, factor: Int) gets recipe without mut or var.
  2. The body may read recipe.servings but cannot assign to it.
  3. Back in main, chili is untouched and prints its original values.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
281
Tokens
69
Three-star pace
80 tpm

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

Type this snippet

Step 4 of 5 in Value semantics, step 9 of 22 in Structs & traits.

← Previous Next →