typestar

Defining functions in Mojo

Every Mojo function is a def with typed arguments.

def area(width: Float64, height: Float64) -> Float64:
    return width * height

def describe(name: String, value: Float64) -> String:
    return name + " = " + String(value)

def main():
    print(describe("area", area(3.0, 4.5)))
    print(describe("square", area(2.0, 2.0)))

How it works

  1. area takes two Float64 arguments and returns one.
  2. The -> Float64 annotation states the return type up front.
  3. main feeds the result of area straight into describe.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
261
Tokens
76
Three-star pace
90 tpm

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

Type this snippet

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

← Previous Next →

Defining functions in other languages