Mojo Functions
Overview
In this tutorial, we will learn about Mojo Functions. A Mojo function is a self-contained block of code that performs a specific task. Functions organize code into manageable pieces to improve readability and promote reusability.
Mojo Functions
We can use the following keywords to declare Mojo Functions:
- fn
- def
The fn function enforces strict type checking and memory safety by requiring explicit type declaration and preventing accidental argument mutation.
Example
Let’s understand using an example. The code example snippet has two functions. One function is defined using the “def” keyword, and the other uses the “fn” keyword.
# Mojo function to add two numbers
# Mojo Tutorials — www.TestingDocs.com
def add(x: Int, y: Int) -> Int:
return x + y
# Entry point of the program
fn main():
try:
var result = add(7,9)
print(result)
except:
print(“Error”)
Save, compile, and run the Mojo code. This should print the result 16 on the screen.
Now change the code line:
from
var result = add(7,9)
to
var result = add(7,9.5)