🔥 Mojo Tutorial 1
Install, setup, basics
Mojo is a programming language developed for the MLIR compiler framework that provides a unified programming framework for software development, especially in the field of artificial intelligence. (from Wiki)
Mojo is a new programming language that bridges the gap between research and production by combining Python syntax and ecosystem with systems programming and metaprogramming features. Mojo is still young, but it is designed to become a superset of Python over time. (from github)
Introduction
This will be a series of tutorials and most of the examples are from official Mojo tutorials.
https://docs.modular.com/mojo/
Install
It is easy to install on your PC and supports Mac, Linux and Windows. Simply follow the instruction on the offical website to install it. https://www.modular.com/mojo
I highly recommend to use VSCODE for development. Mojo extension is available on VSCODE.
Hello World
1 | let hello = "hello world" |
You can also type mojo in your terminal to enter REPL session.
Build an executable binary
create executable
1
mojo build main.mojo
run executable
1
2
3./main
outout: hello world
Basics
Mojo is a complied language and Mojo code can be ahead-of-time (AOT) or just-in-time (JIT) compiled.
fn
keyword is the function definition in Mojo. var
defines a mutable variable. let
creates an immutable value.
1 | fn main(): |
Int
is declared as the type for function arguments and return type.
1 | fn add(x: Int, y: Int) -> Int: |
Functions also takes default values.
1 | fn pow(base: Int, exp: Int = 2) -> Int: |
Function Argument mutability and ownership
Function arguments are immutable references by defualt. This ensures memory safe and avoiding a copy.
This default behavior is called borrowing
and can be explicitly defined using keyword borrowed
.
1 | fn add(borrowed x: Int, borrowed y: Int) -> Int: |
If you want the arguments to be modified within the function. Use keyword inout
for arguments declaration.
Changes made in the function are also visible outside the function.
1 | fn add_inout(inout x: Int, inout y: Int) -> Int: |
owned
keyword provides the function with full ownership of the value. ‵text‵ is a copy of original a
and can be modified without affecting a
.
1 | fn set_fire(owned text: String) -> String: |
If you want to give the function ownership of a value and do not want to make a copy (memory efficient). Use ^
transfer operator.
The transfer operator will destroy local variable, in this case a
. Any later operations that use a
will cause compiler errors.
1 | fn set_fire(owned text: String) -> String: |
Struct in Mojo
A struct
is similar to class
. It supports method, filed, overloading, etc.
Mojo structs are completely static—they are bound at compile-time.
1 | struct Base: |
Python integration
Use Python Numpy
modules in Mojo. If you encounter errors, this may help. https://github.com/modularml/mojo/issues/551
1 | from python import Python |
References
🔥 Mojo Tutorial 1