Skip to content

Mojo Cheat Sheet

This page packs the syntax from the whole tutorial onto one screen, so you can look things up quickly. It follows the same order as the sidebar. Every program here was compiled and run with Mojo 1.2, and the output under it is what we got. When you need the “why” behind a line, follow the link to its lesson.

Task Command
New project with Mojo uv init app && cd app && uv add mojo
Run a file mojo run hello.mojo (or uv run mojo run hello.mojo)
Build an executable mojo build hello.mojo -o hello
Set a compile-time flag mojo run -D ASSERT=all hello.mojo (flags go before the file)
Format code mojo format hello.mojo
Docstrings to JSON mojo doc geometry.mojo -o api.json
Package a folder mojo precompile mylib -o mylib.mojoc
Debugger mojo debug hello.mojo
Check the version mojo --version

More in Mojo Get Started, Mojo Tools & Setup and Mojo Building & Compilation Targets.

Variables, numbers, strings and conversions in one program:

from std.math import sqrt
comptime MAX_USERS = 100 # compile-time constant
def main() raises:
# Variables: a new name needs var
var count = 10 # Int (type inferred)
var price: Float64 = 9.99 # explicit type
var name = "Ada" # String
var ok = True # Bool
var big: Int64 = 1_000_000
count += 1
print(count, price, name, ok, big, MAX_USERS)
# Numbers: / on two Int variables stays an Int
var a = 7
var b = 2
print(a / b, a // b, a % b, a**2)
print(Float64(a) / Float64(b), round(3.14159, 2), sqrt(16.0))
# Strings
var s = "Hello, Mojo"
print(s.upper(), s.byte_length(), "Mojo" in s)
print(s[byte=0:5], s.replace("Mojo", "World"))
print(t"{name} has {count} items")
print("-" * 10, ", ".join(["a", "b", "c"]))
var words = "one two three".split(" ")
print(len(words), words[1])
# Conversions (Int("42") can raise, so main is raises)
var n = Int("42")
print(n + 1, String(3.5), Float64("2.5"), Int(price), Bool(0))
# print options
print("a", "b", sep="-", end="!\n")

Output:

11 9.99 Ada True 1000000 100
3 3 1 49
3.5 3.14 4.0
HELLO, MOJO 11 True
Hello Hello, World
Ada has 11 items
---------- a, b, c
3 two
43 3.5 2.5 9 False
a-b!

Things to remember:

  • len(s) on a String doesn’t compile. Use s.byte_length() or s.count_codepoints().
  • s[0] doesn’t compile either. Pick a unit: s[byte=0], s[codepoint=0] or s[grapheme=0].
  • t-strings take no format specs ({x:.2f} fails). Round first: round(x, 2).
  • "Age: " + 36 is an error. Write "Age: " + String(36).
  • Integer math wraps silently on overflow. See Mojo Integer Overflow.

Lessons: Variables, Numbers, Strings, Type Conversion, Constants, String Formatting.

def grade(score: Int) -> String:
if score >= 90:
return "A"
elif score >= 75:
return "B"
else:
return "C"
def power(base: Int, exp: Int = 2) -> Int: # default value
return base**exp
def total(*nums: Int) -> Int: # any number of arguments
var sum = 0
for n in nums:
sum += n
return sum
def min_max(xs: List[Int]) -> Tuple[Int, Int]: # two results
var lo = xs[0]
var hi = xs[0]
for x in xs:
lo = min(lo, x)
hi = max(hi, x)
return (lo, hi)
def main():
print(grade(80), power(3), power(2, exp=10), total(1, 2, 3))
var i = 0
while i < 3:
i += 1
print("i =", i)
for k in range(0, 10, 3):
if k == 6:
continue
print(k, end=" ")
print()
var fruits: List[String] = ["apple", "kiwi"]
for idx, f in enumerate(fruits):
print(idx, f)
for f in fruits:
if f == "mango":
break
else:
print("no mango") # runs when the loop didn't break
var day = 6
match day:
case 6 | 7:
print("weekend")
case _:
print("weekday")
var lo, hi = min_max([7, 3, 9])
print(lo, hi)
var double = lambda (x: Int) -> Int: x * 2
print(double(21))

Output:

B 9 1024 6
i = 3
0 3 9
0 apple
1 kiwi
no mango
weekend
3 9
42

Things to remember:

  • A function that can fail needs raises in its signature: def parse(s: String) raises -> Int:.
  • Returning a local List or Dict needs return xs^. Int and String don’t.
  • Loop variables are read-only. Use for ref x in xs: to change items in place.
  • match is a statement, not an expression. There’s no labelled break.

Lessons: If…Else, For, Break/Continue, Match, Functions, Function Arguments, Lambdas.

from std.collections import Set
def main() raises:
# List
var nums: List[Int] = [3, 1, 2]
nums.append(5)
print(nums, len(nums), nums[0], nums[len(nums) - 1])
sort(nums)
print(nums, 2 in nums)
var last = nums.pop()
print(last, nums)
var squares = [x * x for x in nums]
print(squares)
var copy = nums.copy() # `var copy = nums` would not compile
copy[0] = 100
print(nums[0], copy[0])
# Dict
var ages: Dict[String, Int] = {"Ana": 30, "Bo": 25}
ages["Cy"] = 41
print(ages["Ana"], len(ages), "Bo" in ages) # ages[key] can raise
print(ages.get("Zed").or_else(0))
for item in ages.items():
print(item.key, item.value)
# Set (needs the import)
var seen = Set[Int]()
seen.add(1)
seen.add(1)
seen.add(2)
print(len(seen), 2 in seen)
# Tuple
var pair = ("x", 10)
print(pair[0], pair[1])
# Optional
var maybe: Optional[Int] = None
if not maybe:
print("empty")
maybe = 7
print(maybe.value())
# Array: fixed size
var arr: Array[Int, 3] = [1, 2, 3]
print(arr[1], len(arr))

Output:

[3, 1, 2, 5] 4 3 5
[1, 2, 3, 5] True
5 [1, 2, 3]
[1, 4, 9]
1 100
30 3 True
0
Ana 30
Bo 25
Cy 41
2 True
x 10
empty
7
2 3

Things to remember:

  • [1, 2, 3] on its own is a fixed-size Array. Write var xs: List[Int] = [1, 2, 3] to get a list.
  • No negative indexes: use xs[len(xs) - 1], not xs[-1].
  • List has no .sort() method. Call sort(xs), or sort(xs, lambda (a: Int, b: Int) -> Bool: a > b) for your own order.
  • for k, v in d.items() doesn’t compile. Use item.key and item.value.

Lessons: Lists, Dictionaries, Sets, Tuples, Optional, Arrays, Span, Sorting & Searching.

trait Shape:
def area(self) -> Float64:
...
def name(self) -> String: # default method
return "shape"
@fieldwise_init
struct Point(Copyable, Equatable, Writable):
var x: Int
var y: Int
def __add__(self, other: Self) -> Self:
return Point(self.x + other.x, self.y + other.y)
def __eq__(self, other: Self) -> Bool:
return self.x == other.x and self.y == other.y
def write_to(self, mut writer: Some[Writer]):
writer.write("(", self.x, ", ", self.y, ")")
@fieldwise_init
struct Square(Shape):
var side: Float64
def area(self) -> Float64:
return self.side * self.side
struct Counter:
var count: Int
def __init__(out self):
self.count = 0
def bump(mut self): # mut self: the method changes the struct
self.count += 1
@staticmethod
def zero() -> Int:
return 0
def describe[T: Shape](s: T):
print(s.name(), s.area())
def main():
var p = Point(1, 2) + Point(3, 4)
print(p, p == Point(4, 6))
var c = Counter()
c.bump()
print(c.count, Counter.zero())
describe(Square(3.0))

Output:

(4, 6) True
1 0
shape 9.0

Things to remember:

  • Fields can’t have defaults (var x: Int = 0 fails). Set them in __init__.
  • To print your struct, conform to Writable. __str__ and Stringable are gone.
  • No classes and no inheritance. Traits describe what a type can do.
  • Lifecycle methods: def __init__(out self, *, copy: Self) for copies, def __init__(out self, *, deinit move: Self) for moves, def __deinit__(deinit self) for clean-up.

Lessons: Structs, Methods, Special Methods, Operator Overloading, Printing Your Types, Traits, Common Traits.

You write What it means
def f(x: T) Read-only reference (the default)
def f(mut x: T) Can change the caller’s value
def f(var x: T) Takes ownership (a copy, or a move with ^)
def f(ref x: T) Reference that keeps the caller’s mutability
def __init__(out self) Output argument: the function sets it up
def __deinit__(deinit self) The value is being destroyed
value^ Moves the value; the old name can’t be used after
value.copy() An explicit copy
@fieldwise_init
struct ParseError(Writable):
var line: Int
def parse(text: String) raises ParseError -> Int: # typed error
if text == "":
raise ParseError(1)
return 42
def show(xs: List[Int]): # read-only
print(len(xs))
def add_one(mut xs: List[Int]): # changes the caller's list
xs.append(1)
def consume(var xs: List[Int]): # takes ownership
xs.append(99)
print(xs)
def make() -> List[Int]:
var xs: List[Int] = [1, 2]
return xs^ # move it out
def main() raises:
var xs = make()
show(xs)
add_one(xs)
consume(xs.copy()) # pass a copy, keep xs
consume(xs^) # hand it over; xs is gone after this
try:
_ = parse("")
except e:
print("parse failed on line", e.line)
try:
raise Error("disk full")
except e:
print("caught:", e)
finally:
print("cleanup")

Output:

2
[1, 2, 1, 99]
[1, 2, 1, 99]
parse failed on line 1
caught: disk full
cleanup

Things to remember:

  • One except per try. main can only raise the plain Error type.
  • An unhandled error prints Unhandled exception caught during execution: <message> and exits with code 1.
  • debug_assert and assert are off unless you build with -D ASSERT=all.

Lessons: Argument Conventions, Moving Values, Value Lifecycle, Errors, Try/Except, Custom Errors.

from std.python import Python
def biggest[T: Comparable & ImplicitlyCopyable](a: T, b: T) -> T:
return a if a > b else b
def repeat[count: Int](msg: String):
comptime for _ in range(count): # unrolled at compile time
print(msg, end=" ")
print()
def batches[size: Int](total: Int) -> Int where size > 0:
return (total + size - 1) // size
def main() raises:
print(biggest(3, 7), biggest("pear", "apple"))
repeat[3]("hi")
print(batches[10](95))
comptime DEBUG = False
comptime if DEBUG:
print("debug build")
var v = SIMD[DType.float32, 4](1, 2, 3, 4)
print(v * 2, v.reduce_add(), len(v))
var math = Python.import_module("math")
var r = math.sqrt(16)
print(r, Float64(py=r) + 1)

Output:

7 pear
hi hi hi
10
[2.0, 4.0, 6.0, 8.0] 10.0 4
4.0 5.0

Things to remember:

  • Square brackets [...] hold parameters (known at compile time), round brackets hold arguments.
  • comptime if and comptime for replace the old @parameter if/for.
  • vectorize is in std.algorithm. parallelize and the GPU APIs are in Modular’s separate max package.
  • Convert Python values back with Int(py=obj), Float64(py=obj) or String(py=obj).

Lessons: Compile-Time Code, Parameters, Generics, Constraints, SIMD, Vectorize, Calling Python.

from std.sys import argv
from std.os import getenv, remove
from std.pathlib import Path
def main() raises:
var args = argv() # args[0] is the program itself
print("args:", len(args))
print("mode:", getenv("APP_MODE", "dev"))
with open("notes.txt", "w") as f:
f.write("first line\n")
with open("notes.txt", "a") as f:
f.write("second line\n")
print(open("notes.txt", "r").read().splitlines())
print(Path("notes.txt").read_text().count("line"))
remove("notes.txt")

Output:

args: 1
mode: dev
[first line, second line]
2

A test file is a normal program. There’s no mojo test command, so you run it with mojo run:

from std.testing import assert_equal, assert_raises, TestSuite
def double(x: Int) -> Int:
return x * 2
def test_double() raises:
assert_equal(double(4), 8)
def test_bad_number() raises:
with assert_raises():
_ = Int("abc")
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()

It prints one PASS line per test and a summary. More in Mojo Testing, Mojo File I/O, Mojo Command-Line Arguments and Mojo Modules & Packages.

  • New names need var; constants use comptime; functions use def, plus raises if they can fail.
  • Lists need a type: var xs: List[Int] = [...]; sort with sort(xs); no negative indexes.
  • Strings have no len() or s[0]: use byte_length() and s[byte=0].
  • Structs get @fieldwise_init, traits like Copyable and Writable, and no inheritance.
  • Arguments are read-only by default; mut, var and ^ change that.

Next up: Mojo for Python Cheat Sheet, the same kind of page as a two-column Python vs Mojo table.

Quick check

1. Which line makes a growable list of numbers?
2. How do you sort a List[Int] called nums?
3. What does a function need before it can call Int("42")?