typestar

Default and keyword arguments in Mojo

Defaults let one function cover several call shapes.

def greet(name: String, greeting: String = "Hello",
          mark: String = "!") -> String:
    return greeting + ", " + name + mark

def main():
    print(greet("Mojo"))
    print(greet("Mojo", greeting="Welcome"))
    print(greet("world", mark="?"))

How it works

  1. greeting and mark carry defaults, so greet("Mojo") stands alone.
  2. Naming an argument at the call site overrides just that default.
  3. Keyword arguments may appear in any order after the positional ones.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
226
Tokens
76
Three-star pace
85 tpm

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

Type this snippet

Step 4 of 6 in Variables & functions, step 4 of 26 in Language basics.

← Previous Next →