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.
Commands
Section titled “Commands”| 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.
Basics
Section titled “Basics”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 1003 3 1 493.5 3.14 4.0HELLO, MOJO 11 TrueHello Hello, WorldAda has 11 items---------- a, b, c3 two43 3.5 2.5 9 Falsea-b!Things to remember:
len(s)on aStringdoesn’t compile. Uses.byte_length()ors.count_codepoints().s[0]doesn’t compile either. Pick a unit:s[byte=0],s[codepoint=0]ors[grapheme=0].- t-strings take no format specs (
{x:.2f}fails). Round first:round(x, 2). "Age: " + 36is 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.
Control flow and functions
Section titled “Control flow and functions”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 6i = 30 3 90 apple1 kiwino mangoweekend3 942Things to remember:
- A function that can fail needs
raisesin its signature:def parse(s: String) raises -> Int:. - Returning a local
ListorDictneedsreturn xs^.IntandStringdon’t. - Loop variables are read-only. Use
for ref x in xs:to change items in place. matchis a statement, not an expression. There’s no labelledbreak.
Lessons: If…Else, For, Break/Continue, Match, Functions, Function Arguments, Lambdas.
Collections
Section titled “Collections”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] True5 [1, 2, 3][1, 4, 9]1 10030 3 True0Ana 30Bo 25Cy 412 Truex 10empty72 3Things to remember:
[1, 2, 3]on its own is a fixed-sizeArray. Writevar xs: List[Int] = [1, 2, 3]to get a list.- No negative indexes: use
xs[len(xs) - 1], notxs[-1]. Listhas no.sort()method. Callsort(xs), orsort(xs, lambda (a: Int, b: Int) -> Bool: a > b)for your own order.for k, v in d.items()doesn’t compile. Useitem.keyanditem.value.
Lessons: Lists, Dictionaries, Sets, Tuples, Optional, Arrays, Span, Sorting & Searching.
Structs and traits
Section titled “Structs and traits”trait Shape: def area(self) -> Float64: ...
def name(self) -> String: # default method return "shape"
@fieldwise_initstruct 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_initstruct 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) True1 0shape 9.0Things to remember:
- Fields can’t have defaults (
var x: Int = 0fails). Set them in__init__. - To
printyour struct, conform toWritable.__str__andStringableare 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.
Ownership and errors
Section titled “Ownership and errors”| 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_initstruct 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 1caught: disk fullcleanupThings to remember:
- One
exceptpertry.maincan only raise the plainErrortype. - An unhandled error prints
Unhandled exception caught during execution: <message>and exits with code 1. debug_assertandassertare off unless you build with-D ASSERT=all.
Lessons: Argument Conventions, Moving Values, Value Lifecycle, Errors, Try/Except, Custom Errors.
Compile time, SIMD and Python
Section titled “Compile time, SIMD and Python”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 pearhi hi hi10[2.0, 4.0, 6.0, 8.0] 10.0 44.0 5.0Things to remember:
- Square brackets
[...]hold parameters (known at compile time), round brackets hold arguments. comptime ifandcomptime forreplace the old@parameter if/for.vectorizeis instd.algorithm.parallelizeand the GPU APIs are in Modular’s separatemaxpackage.- Convert Python values back with
Int(py=obj),Float64(py=obj)orString(py=obj).
Lessons: Compile-Time Code, Parameters, Generics, Constraints, SIMD, Vectorize, Calling Python.
Real programs and tests
Section titled “Real programs and tests”from std.sys import argvfrom std.os import getenv, removefrom 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: 1mode: dev[first line, second line]2A 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 usecomptime; functions usedef, plusraisesif they can fail. - Lists need a type:
var xs: List[Int] = [...]; sort withsort(xs); no negative indexes. - Strings have no
len()ors[0]: usebyte_length()ands[byte=0]. - Structs get
@fieldwise_init, traits likeCopyableandWritable, and no inheritance. - Arguments are read-only by default;
mut,varand^change that.
Next up: Mojo for Python Cheat Sheet, the same kind of page as a two-column Python vs Mojo table.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo cheat sheets: the official quick-reference cards, one per topic.
- Basics cheat sheet: syntax essentials on one page.
- Ownership cheat sheet: argument conventions and moves at a glance.
- Mojo language reference: the exact rules for every statement and declaration.
- Mojo standard library: every type and function that ships with Mojo.