Version: 1.1.0

Functions

Mojo functions are declared with def or fn. Both can be called the same way. def is the flexible form, closer to Python, and fn asks for stricter types and argument conventions.

Essentials

  • Every program starts at def main(): or fn main():.
  • def arguments default to values you can read. Add mut when the function must write through the argument.
  • A return type is written with ->. Omit it only when the function returns nothing.
  • raises marks a function that can produce an error value.
  • Overloading is allowed: two functions may share a name when their arguments differ.

Example

def greet(name: String) -> String:
    return "Hello, " + name

def main():
    print(greet("Mojo"))

Keep in mind

Use fn on hot paths when you want the compiler to require explicit copies and argument conventions. Use def while you are exploring an API.