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
scaled(recipe: Recipe, factor: Int)getsrecipewithoutmutorvar.- The body may read
recipe.servingsbut cannot assign to it. - Back in
main,chiliis untouched and prints its original values.
Keywords and builtins used here
IntMovableStringdefmainprintreturnscaledstructvar
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.
Step 4 of 5 in Value semantics, step 9 of 22 in Structs & traits.