How to Define Functions in Mojo: Parameters, Type Annotations, and Return Values

Mojo

Function Definitions in Mojo

Functions are a core building block in any programming language, and Mojo introduces a familiar yet type-safe way of defining them. In this article, we’ll look at how to define functions, use typed parameters, and specify return types. If you’re coming from Python, you’ll find the syntax both intuitive and more explicit.

Basic Function Syntax

A simple function in Mojo is defined using the fn keyword, followed by the function name, typed parameters, and a return type:

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

In this example:

  • name: String defines the parameter and its type
  • -> String declares the return type

Multiple Parameters

Mojo supports multiple typed parameters, just like Python but with stricter type safety:

fn add(a: Int, b: Int) -> Int:
    return a + b

Return Types

You can explicitly define the type that the function should return. This improves performance and makes code easier to understand. If a function doesn’t return anything, you can use None:

fn log_message(msg: String) -> None:
    print(msg)

Default Parameter Values (Upcoming Feature)

As of current Mojo versions, default parameter values may not yet be supported, but the syntax may look similar to Python in future versions. Stay tuned to the official documentation.

Comparing with Python

Here’s a comparison of a function in Python vs Mojo:

PythonMojo
def add(a, b): return a + bfn add(a: Int, b: Int) -> Int: return a + b

Summary

  • Use fn to define a function
  • Each parameter must include a type annotation
  • Use -> Type to specify return values
  • Clear syntax improves performance and readability

In the next article, we’ll explore control structures like if, for, and while in Mojo.

I would like to put together a comparison between Python and Mojo next time.

Comment

Copied title and URL