Logo
vii.ms

Mojo Basic Syntax

May 29th,2024

Mojo Basic Syntax

Mojo Basic Syntax

>> mojo --version     
mojo 24.3.0 (9882e19d)
>> vi syntax.mojo

Main

fn main():
    print("Hello world")
>> mojo syntax.mojo

Function

Mojo functions can be declared with either fn or def.

The fn declaration enforces type-checking and memory-safe behaviors (Rust style), while def allows no type declarations and dynamic behaviors (Python style).

*** please use fn style. ***

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

fn main():
    print("Hello world")
    var response: String = greet("John")
    print(response)

Compare

fn compare(guess: Int):
    var the_magic_number : Int = 10

    if guess < the_magic_number:
        print(guess, "is too low!")
    elif guess > the_magic_number:
        print(guess, "is too high!")
    else:
        print("You guessed correct!")

Loop

fn loop(max: Int):
    for i in range(max):
    print(i)

Array

fn array():
    var list = [1, 3.0,"Mojo"]
    print(list.get[2, StringLiteral]())
    var tup = (1, "Mojo", 3.14)
    print(tup.get[0, Int]())
    print(len(tup))