You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Current Stable Release: Mojo 1.0.0 (Released May 7, 2026) Stability Status: Production-ready with API stability guarantees Package Version: 25.7.0+ (Modular Platform 26.5) Open Source Status: Standard library open source (Apache 2.0), Compiler open sourcing Fall 2026
# Mutable variable (v1.0: var is now required)varx: Int =10# Explicitly typedvary=20# Type inferredvarz: Float64 # Uninitialized (must be assigned before use)# Reference binding
ref view = data # Immutable reference to existing value
ref mut_view = mut data # Mutable reference# Compile-time constantsaliasMAX_SIZE=100# Compile-time constantaliasMyType= Int64 # Type alias
4.2 Conventions in Variable Declarations
Convention
Syntax
Meaning
var
var x = value
Owned mutable copy
ref
ref x = value
Reference (borrows)
mut
mut x
Mutable reference
imm
imm x
Immutable reference (default)
out
out x
Output parameter
deinit
deinit x
Destructive transfer
5. Functions
5.1 Function Declaration Syntax
# Basic functiondeffunction_name(arg1: Type1, arg2: Type2) -> ReturnType:
"""Docstring"""return result
# Function with effectsdefraising_function() raises:
raise Error("message")
# Function with constraintsdefconstrained[T: Trait](value: T) whereconforms_to(T, Sized):
pass# Lambda expression (v1.0+)varadd=lambda (x: Int, y: Int) -> Int: x + y
varnoop=lambda: None
5.2 Argument Conventions
# Immutable borrow (default)fnfunc(value: Int): # imm is implicit# Mutable borrowfnfunc(mutvalue: Int):
value +=1# Take ownershipfnfunc(owned value: Int):
# value is destroyed when func returns# Output parameterfnmake_value(outresult: Int):
result =42# Variadic argumentsdeffunc(*args: Int):
for arg in args:
print(arg)
# Keyword variadic arguments (v1.0: must use var)deffunc(var**kwargs: Int):
for key, value in kwargs.items():
print(key, value)
# Forwarding variadics (v1.0)defwrapper(var**kwargs: Int):
inner_function(**kwargs^)
5.3 Function Effects
Effect
Syntax
Description
raises
def f() raises:
Function may raise errors
capturing
def f() capturing:
Closure captures environment
async
async def f():
Async function
5.4 Generic Functions
# Simple genericfnidentity[T: AnyType](value: T) -> T:
return value
# Constrained genericfnprocess[T: Movable & Copyable](value: T) -> T:
return value
# Multiple type parametersfnpair[T: AnyType, U: AnyType](a: T, b: U) -> Tuple[T, U]:
return (a, b)
# Variadic genericsfnprocess_all[*Ts: Movable](*args: *Ts):
pass# Where clause with message (v1.0+)fnscale[sc: Int]() where (sc > 1, "scaling factor must be > 1"):
pass
structMath:
@staticmethodfnpi() -> Float64:
return3.14159265359@staticmethodfnmax[T: Comparable](a: T, b: T) -> T:
return a if a > b else b
7. Traits
7.1 Trait Declaration
traitDrawable:
"""Objects that can be drawn."""# Required method (no implementation)fndraw(self):
...# Optional method (with default implementation)fnarea(self) -> Float64:
return0.0traitMovable:
fn__moveinit__(outself, owned existing: Self):
...traitCopyable:
fn__copyinit__(outself, existing: Self):
...traitDeinitable: # v1.0: renamed from ImplicitlyDestructiblefn__deinit__(deinit self):
...
7.2 Built-in Traits
Trait
Description
Methods
AnyType
Top trait (all types)
None
Movable
Can be moved
__moveinit__
Copyable
Can be copied
__copyinit__
ImplicitlyCopyable
Can be implicitly copied
__copyinit__
Deinitable
Has destructor (v1.0)
__deinit__
Equatable
Can be compared for equality
__eq__
Comparable
Can be ordered
__lt__, __le__, __gt__, __ge__
Hashable
Can be hashed
__hash__
Stringable
Can be converted to string
__str__
Writable
Can be written to writer
write_to
Sized
Has size/length
__len__
Iterable
Can be iterated
__iter__
Iterator
Is an iterator
__next__, __has_next__
CollectionElement
Can be in collections
Various
KeyElement
Can be dict key
__hash__, __eq__
Intable
Can convert to Int
__int__
Floatable
Can convert to Float
__float__
Indexable
Supports indexing
__getitem__
8. Standard Library APIs
8.1 Core Collections
Array (Fixed-size)
from std.collections import Array
# Constructionvararr= Array[Int, 5]() # Default constructedvararr2= Array[Int, 3](1, 2, 3) # With initial valuesvararr3: Array[Int, _] = [1, 2, 3] # Type inference# Properties
arr.length # Number of elements (v1.0: size -> length)# Indexing
arr[0] # Get element
arr[0] =10# Set element# Methods
arr.copy() # Copy array
arr.unsafe_ptr() # Get raw pointer
List (Dynamic)
from std.collections import List
# Constructionvarlst= List[Int]() # Empty listvarlst2= List[Int](capacity=100) # With capacityvarlst3: List = [1, 2, 3] # From literal (v1.0: now constructs Array, use explicit type)# Propertieslen(lst) # Number of elements
lst.capacity() # Current capacity (v1.0: now method)# Methods
lst.append(value) # Add element
lst.extend(other) # Extend with iterable
lst.insert(index, value) # Insert at index
lst.pop() # Remove and return last
lst.pop(index) # Remove at index
lst.remove(value) # Remove first occurrence
lst.clear() # Remove all elements
lst.clear_with(destroy_func) # Clear with custom destructor (v1.0)
lst.find(value) # Find index (raises if not found)
lst.try_index(value) # Find index (returns Optional)
lst.resize(new_length) # Resize (v1.0: new_size -> new_length)
lst.shrink(new_length) # Shrink capacity
lst.copy() # Shallow copy
lst.reverse() # Reverse in place
lst.sort() # Sort in place
lst.deinit_with(func) # Destroy with function (v1.0)# Iterationfor item in lst: # By referencefor item in lst^: # Consuming (takes ownership)
Dict (Hash Map)
from std.collections import Dict
# Constructionvard= Dict[String, Int]() # Empty dictvard2= Dict[String, Int]({"a": 1}) # With initial values# Propertieslen(d) # Number of entries# Access
d["key"] # Get (raises if missing)
d.get("key", default=0) # Get with default
d.setdefault("key", default=0) # Set if missing# Methods
d.insert(key, value) # Insert, returns displaced (v1.0)
d.update(other) # Update with other dict
d.pop(key) # Remove and return
d.pop(key, default) # Remove with default
d.clear() # Remove all
d.clear_with(destroy_func) # Clear with destructor (v1.0)
d.keys() # Iterator over keys
d.values() # Iterator over values
d.items() # Iterator over (key, value)
d.take_items() # Consuming iterator (v1.0: renamed from take)# Membership"key"in d # Check key exists
Set
from std.collections import Set
# Constructionvars= Set[Int]() # Empty setvars2= Set[Int]([1, 2, 3]) # From iterable# Methods
s.add(element) # Add element
s.remove(element) # Remove (raises if missing)
s.discard(element) # Remove (no error)
s.pop() # Remove and return arbitrary
s.clear() # Remove all
s.clear_with(destroy_func) # Clear with destructor (v1.0)
s.union(other) # Union
s.intersection(other) # Intersection
s.difference(other) # Difference
s.symmetric_difference(other) # Symmetric difference# Operators
s1 | s2 # Union
s1 & s2 # Intersection
s1 - s2 # Difference
s1 ^ s2 # Symmetric difference# Membership
element in s # Check membership
Optional
from std.collections import Optional
# Constructionvaropt: Optional[Int] =None# Emptyvaropt2= Optional(42) # With valuevaropt3: Optional[Int] =42# Implicit conversion# Methods
opt.is_none() # Check if None
opt.is_some() # Check if has value
opt.value() # Get value (raises if None)
opt.take() # Take value (consuming)
opt.unwrap[T]() # Unwrap as T (v1.0: renamed from take[T])
opt.map(func) # Transform if Some
opt.and_then(func) # Chain operations
opt.or_else(default) # Provide default
opt.deinit_with(func) # Destroy with function (v1.0)
opt.deinit_assert_empty() # Assert empty and destroy (v1.0)# Pattern matchingif opt:
print(opt.value()) # Safe inside if
Span (View)
from std.collections import Span, MutSpan, ImmSpan
# Constructionvarspan= Span(lst) # From listvarspan2= Span(unsafe_ptr=ptr, length=n) # From pointer (v1.0: ptr -> unsafe_ptr)varspan3= arr.as_span() # From array# Properties
span.length # Number of elements
span.is_empty() # Check if empty# Indexing
span[i] # Get element
span[start:end] # Slice (v1.0: stricter bounds checking)# Methods
span.first() # First element
span.last() # Last element
span.as_imm() # Convert to immutable (v1.0: renamed from as_immutable)
span.unsafe_ptr() # Get raw pointer
span.fill(value) # Fill with value
span.copy_from(other) # Copy from other span
span.find(value) # Find element
span.reverse() # Reverse view
8.2 String APIs
from std.collections import String, StringSpan
# Constructionvars= String("hello") # From literalvars2= String(42) # From numbervars3= String.format("{}", value) # Formatted# Properties
s.length # Number of bytes (UTF-8)
s.byte_length() # Same as length
s.count_codepoints() # Number of Unicode scalars
s.count_graphemes() # Number of user-perceived characters (v1.0: default iteration)
s.is_empty() # Check if empty# Indexing (v1.0: stricter bounds)
s[byte=i] # Byte at offset
s[codepoint=i] # Unicode scalar
s[grapheme=i] # User-perceived character
s[i:j] # Byte slice# Iteration (v1.0: yields graphemes by default)for char in s: # Grapheme clustersfor cp in s.codepoints(): # Unicode scalarsfor byte in s.bytes(): # Raw bytes# Methods
s.append(other) # Append string
s.extend(other) # Extend with chars
s.insert(index, char) # Insert character
s.find(substring) # Find substring
s.rfind(substring) # Find from right
s.startswith(prefix) # Check prefix
s.endswith(suffix) # Check suffix
s.strip() # Remove whitespace
s.lstrip() # Remove leading whitespace
s.rstrip() # Remove trailing whitespace
s.split(sep) # Split into list
s.join(iterable) # Join with separator
s.replace(old, new) # Replace substring
s.lower() # To lowercase
s.upper() # To uppercase
s.is_digit() # Check if all digits
s.is_alpha() # Check if all letters
s.is_alnum() # Check if alphanumeric
s.to_int() # Parse as integer
s.to_float() # Parse as float
s.as_span() # As StringSpan
s.copy() # Copy string
8.3 Numeric APIs
from math import sqrt, sin, cos, tan, exp, log, powfrom math import pi, e, inf, nan
# Constants
pi # 3.14159...
e # 2.71828...
inf # Infinity
nan # Not a number# Functions
sqrt(x) # Square root
sin(x), cos(x), tan(x) # Trigonometric
asin(x), acos(x), atan(x) # Inverse trig
sinh(x), cosh(x), tanh(x) # Hyperbolic
exp(x) # Exponential
log(x) # Natural log
log2(x), log10(x) # Log base 2, 10pow(x, y) # Powerabs(x) # Absolute valuemin(a, b), max(a, b) # Min/max
floor(x), ceil(x), trunc(x), round(x) # Rounding
hypot(x, y) # Hypotenuse
expm1(x) # exp(x) - 1
8.4 SIMD Operations
from std.builtin importSIMD# Constructionvarvec=SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)
varzeros=SIMD[DType.int32, 8].splat(0) # Broadcast value# Arithmetic (element-wise)
vec + other # Addition
vec - other # Subtraction
vec * other # Multiplication
vec / other # Division
vec // other # Floor division
vec % other # Modulo# Comparison (element-wise, returns mask)
vec == other
vec != other
vec < other
vec <= other
vec > other
vec >= other
# Bitwise
vec & other # AND
vec | other # OR
vec ^ other # XOR~vec # NOT# Reductions
vec.reduce_add() # Sum all elements
vec.reduce_mul() # Product
vec.reduce_min() # Minimum
vec.reduce_max() # Maximum
vec.reduce_and() # AND reduction
vec.reduce_or() # OR reduction
vec.reduce_xor() # XOR reduction# Shuffles and swizzles
vec.shuffle[indices...]() # Reorder elements
vec.interleave(other) # Interleave elements
vec.deinterleave() # Deinterleave# Conversions
vec.cast[DType.int32]() # Cast to different dtype
vec.to_bits() # Bit representation
8.5 Range
from std.builtin importrange# Construction (v1.0: unified dtype-parameterized)range(stop) # 0 to stop-1range(start, stop) # start to stop-1range(start, stop, step) # With step# Properties
r.start # Start value
r.stop # Stop value
r.step # Step valuelen(r) # Number of elements (always Int)# Reversalreversed(r) # Reverse range# Iterationfor i inrange(10): # Standard iterationfor i inreversed(range(10)): # Reverse iteration
8.6 I/O Operations
from std.io importopen, FileHandle, stdout, stderr, stdin
# File operationsvarf=open("file.txt", "r") # Open for readingvarf2=open("file.txt", "w") # Open for writingvarf3=open("file.txt", "a") # Open for appendvarf4=open("file.txt", "rw") # Open for read/write# Context managerwithopen("file.txt", "r") as f:
data = f.read()
# FileHandle methods
f.read() # Read entire file
f.read(size) # Read n bytes
f.readline() # Read one line
f.readlines() # Read all lines
f.write(data) # Write string
f.writelines(lines) # Write multiple lines
f.seek(offset, whence) # Seek position (v1.0: Int offset)
f.tell() # Current position
f.flush() # Flush buffer
f.close() # Close file
f.__enter__(), f.__exit__() # Context manager protocol# Standard streamsprint("hello") # Print to stdoutprint("hello", file=stderr) # Print to stderrprint("hello", end="") # No newlineprint("hello", sep=", ") # Custom separator# Formattingfrom std.format importformat, StringWriter
vars=format("{}", value) # Format to stringvarwriter= StringWriter()
writer.write("{}", value)
varresult= writer.get_string()
8.7 OS Operations
from std.os import getenv, setenv, chdir, getcwd, listdir, mkdir, remove, rename
getenv("PATH") # Get environment variable
setenv("KEY", "value") # Set environment variable
chdir("/path") # Change directory (v1.0)
getcwd() # Current directory
listdir("/path") # List directory contents
mkdir("/path") # Create directory
remove("/path") # Remove file
rename("/old", "/new") # Rename file
8.8 Time
from time import now, sleep
varstart= now() # Current time (nanoseconds)
sleep(1.0) # Sleep for seconds
sleep(1000) # Sleep for milliseconds
9. Memory Management
9.1 Pointer Operations
from std.memory import Pointer, OwnedPointer, ArcPointer
# Pointer constructionvarptr= Pointer[Int].alloc(10) # Allocate memoryvarptr2= Pointer[Int].address_of(value) # Get address of variable# Safe operations
ptr[0] # Index (bounds checked in debug)
ptr.length # Get length if known# Unsafe operations (v1.0: prefixed with unsafe_)
ptr.unsafe_load() # Load value
ptr.unsafe_store(value) # Store value
ptr.unsafe_offset(n) # Pointer arithmetic (v1.0: + -> unsafe_offset)
ptr.unsafe_gather(indices) # Gather elements
ptr.unsafe_scatter(values, indices) # Scatter elements
ptr.unsafe_as_noalias() # Mark as no-alias
ptr.unsafe_memcpy(dest, src, count) # Copy memory
ptr.unsafe_free() # Free memory# Allocation (v1.0: new alloc package)from std.memory.alloc import alloc, free, Allocation
varalloc_result= alloc[Int](10) # Allocatevardata= alloc_result.unsafe_ptr() # Get pointer
free(alloc_result) # Free allocation# Owned pointervarowned= OwnedPointer[Int](42) # Owns memoryvarval= owned.into_inner() # Take ownership (v1.0: renamed from take)varalloc= owned.unsafe_take_allocation() # Get allocation (v1.0: renamed from steal_data)# Reference countedvarshared= ArcPointer[Int](42) # Reference countedvarref= shared.copy() # Increment count
9.2 Memory Traits and Types
Type/Trait
Description
AddressSpace
Memory address space (GENERIC, SHARED, etc.)
Origin
Lifetime tracking
ImmOrigin
Immutable origin
MutOrigin
Mutable origin
UntrackedOrigin
No lifetime tracking
UnsafeAnyOrigin
Unsafe escape hatch
10. Control Flow
10.1 If Statements
if condition:
passelif other_condition:
passelse:
pass# Ternary conditionalvarresult= value if condition else default
# Inline if (ternary expression)varx= a if a > b else b
10.2 Loops
# For loopfor i inrange(10):
passfor item in iterable:
passfor i, item inenumerate(iterable):
pass# While loopwhile condition:
pass# Loop with else (executes if no break)for i inrange(10):
if condition:
breakelse:
print("No break")
# Continue and breakfor i inrange(100):
if i <10:
continueif i >20:
breakprint(i)
10.3 Context Managers
with resource as r:
use(r)
# r is cleaned up# Multiple context managerswithopen("a") as f1, open("b") as f2:
pass# Custom context managerstructManagedResource:
fn__enter__(self) -> Self:
returnselffn__exit__(self):
self.cleanup()
11. Error Handling
11.1 Raising Errors
defrisky() raises:
raise Error("Something went wrong")
defrisky_with_trace() raises:
raise Error("Message").with_stack_trace()
11.2 Handling Errors
try:
risky()
except Error as e:
print("Error:", e)
except OtherError:
print("Other error")
except:
print("Any error")
else:
print("No error occurred")
finally:
print("Always runs")
# Re-raisingtry:
risky()
except Error as e:
raise# Re-raise same errorraise Error("Wrapped") from e # Chain errors
11.3 Error Type
from std.builtin import Error
# Constructionvare= Error("message")
vare2= Error("message").with_stack_trace()
# Properties
e.message() # Error message
e.has_stack_trace() # Has trace?
e.get_stack_trace() # Get trace
from std.reflection import reflect
# Type reflectioncomptimeinfo= reflect[MyStruct]
info.name # Type name
info.field["x"].T # Field type (v1.0: renamed from field_type)
info.field_at[0].T # Field by index# Trait checking
conforms_to(T, Movable)
is_trivially_deletable[T]() # Check destructor (v1.0: renamed)# Type functions
TypeList.of[Int, Bool, Float64] # Create type list (v1.0: infers Trait)TL.all_conforms_to[Movable]() # Check all conform
13.3 Parameters
# Compile-time parameterfnprocess[size: Int](data: SIMD[DType.float32, size]):
pass# Type parameter with constraintfnsort[T: Comparable](mutlist: List[T]):
pass# Variadic parametersfntuple_of[*Ts: AnyType](*args: *Ts) -> Tuple[*Ts]:
return args
# Where clausefnscale[sc: Int]() wheresc > 0:
pass# Where with message (v1.0)fnscale[sc: Int]() where (sc > 1, "must be > 1"):
pass
14. Python Interoperability
14.1 Importing Python
from python import Python
# Import modulevarnp= Python.import_module("numpy")
varpd= Python.import_module("pandas")
# Use Python objectsvararr= np.array([1, 2, 3])
varresult= np.sum(arr)
# PythonObject operations (v1.0: 12x faster via protocols)vara= PythonObject(5)
varb= PythonObject(10)
varc= a + b # Uses PyNumber_Addvard= a < b # Uses PyObject_RichComparevare= a in arr # Uses PySequence_Contains# Call Python functions
result = py_func.call(arg1, arg2)
result = py_func(arg1, arg2) # Same
14.2 NumPy Interop (v1.0+)
from std.python.numpy import copy_to_numpy_array, from_numpy_array
# Mojo to NumPyvarmojo_list= List[Float64](1.0, 2.0, 3.0)
varnp_array= copy_to_numpy_array(mojo_list)
# NumPy to Mojo (zero-copy borrow)varnp_arr= numpy_array # Python numpy arrayvarmojo_span= from_numpy_array(np_arr)
Import system overhauled - More explicit resolution
GPU APIs moved to max package - No longer in std
Self type required for methods - Not custom types
Lambda expressions added - Anonymous functions
Appendix C: Quick Reference Card
Common Patterns
# Variable declaration (v1.0: var required)varx: Int =5# Functiondefadd(a: Int, b: Int) -> Int:
return a + b
# Struct with fieldwise init@fieldwise_initstructPoint:
varx: Float64
vary: Float64
# TraittraitDrawable:
fndraw(self):
...# Generic functionfnprocess[T: Movable](value: T):
pass# Error handlingdefrisky() raises:
raise Error("oops")
try:
risky()
except Error as e:
print(e)
# List operationsvarlst= List[Int]()
lst.append(1)
for item in lst:
print(item)
# String operationsvars= String("hello")
for grapheme in s: # v1.0: graphemes by defaultprint(grapheme)
# SIMDvarvec=SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)
varsum= vec.reduce_add()
# Pointer (v1.0: unified)varptr= Pointer[Int].alloc(10)
ptr.unsafe_store(42)
ptr.unsafe_free()
# Python interopvarnp= Python.import_module("numpy")
This reference guide is based on Mojo 1.0.0 released May 7, 2026. For the latest updates, consult the official documentation at https://mojolang.org/docs/