For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
Mojo traits cheat sheet
Lifecycle
AnyTypethe root; every type conforms automaticallytraits/anytype.mojo
no requirements
Deinitablehas an implicit destructor, called at last usetraits/deinitable.mojo
| Signature | Remark |
|---|---|
__deinit__(deinit self, /) | provided |
comptime __del__is_trivial: Bool | compile-time flag |
Automatically added to every eligible type (all fields are also Deinitable). When the type is trivial, Mojo skips the destructor.
Movabletransfer ownership; enables the ^ operatortraits/movable.mojo
| Signature | Remark |
|---|---|
__init__(out self, *, deinit move: Self) | provided |
comptime __move_ctor_is_trivial: Bool | compile-time flag |
Required to store a type in List, Optional, or Variant, or to return it by move.
Copyableexplicit copytraits/copyable.mojo
Refines: Movable
| Signature | Remark |
|---|---|
__init__(out self, *, copy: Self) | provided |
copy(self) -> Self | provided |
comptime __copy_ctor_is_trivial: Bool | compile-time flag |
The copy constructor is synthesized if all fields are Copyable.
ImplicitlyCopyable(MARKER) lets copies be inserted implicitlytraits/copyable.mojo
Refines: Copyable < Movable · no new requirements
Can mask logical errors and hide code reasoning. Prefer Movable or Copyable.
Defaultablecreate with no argumentsbuiltin/value.mojo
| Signature | Remark |
|---|---|
__init__(out self) |
Reach for this when you need parameterized default-construction without arguments.
RegisterPassable(MARKER) stored in registers, not memory; no stable address or identitybuiltin/value.mojo
Refines: Movable · no requirements (marker)
No stable address: you can't take the address of self in imm-convention methods. Identifiable is meaningless for these types.
Moved trivially; all fields must also conform.
TrivialRegisterPassable(MARKER) register-passable, copyable by moving bits, no side effectsbuiltin/value.mojo
Refines: ImplicitlyCopyable < Copyable < Movable, Deinitable, RegisterPassable · no requirements (marker)
A type whose values are treated as basic bit patterns. No constructors or destructors needed. All fields must also conform.
Format
Writableformat itself as text; works with print(), String(), format stringsformat/__init__.mojo
| Signature | Remark |
|---|---|
write_to(self, mut writer: Some[Writer]) | provided |
write_repr_to(self, mut writer: Some[Writer]) | provided |
If all fields conform, you inherit both methods through reflection.
Writera destination for a custom output targetformat/__init__.mojo
String, FileHandle, FileDescriptor conform
| Signature | Remark |
|---|---|
write_string(mut self, string: StringSpan) | |
write[*Ts: Writable](mut self, *args: *Ts) | provided |
Use for loggers, network streams, string builders, etc.
Testing
Strategyproduces random inputs for property-based teststesting/prop/strategy/__init__.mojo
Refines: Deinitable, Movable
| Signature | Remark |
|---|---|
Value: Copyable & Deinitable | associated type |
value(mut self, mut rng: Rng) raises -> Self.Value |
Allows strategies to carry and advance state between draws. value() draws one sample from the random number generator.
Accelerator traits
DevicePassablemarks a type as passable to an acceleratorbuiltin/device_passable.mojo
| Signature | Remark |
|---|---|
comptime device_type: AnyType | the on-device type |
_to_device_type(self, mut enc, ...) | DeviceContext hook |
A host type implements this so it can be handed to a GPU or other accelerator. DeviceContext calls the conversion hook to turn host into device at kernel launch.
DeviceTypeEncoderencodes host values into device layoutbuiltin/device_passable.mojo
| Signature | Remark |
|---|---|
target() -> _TargetType | device target |
encode_device_ptr(mut self, ...) | required |
encode[T](mut self, value, dst) | provided (+ fields, tuple, array) |
Encodes a value's fields into the accelerator's data layout.
Compare & hash
Equatableequality; enables == and !=builtin/comparable.mojo
| Signature | Remark |
|---|---|
__eq__(self, other: Self) -> Bool | provided |
__ne__(self, other: Self) -> Bool | provided |
Don't use with floating-point values (use isclose()). NaN != NaN.
Mojo provides a fieldwise default. Override for caches, internal metadata, and custom behavior.
Comparableordered comparison; < > ≤ ≥, and sort()builtin/comparable.mojo
Refines: Equatable
| Signature | Remark |
|---|---|
__lt__(self, rhs: Self) -> Bool | |
__gt__(self, rhs: Self) -> Bool | provided |
__le__(self, rhs: Self) -> Bool | provided |
__ge__(self, rhs: Self) -> Bool | provided |
Implement __lt__() unless it's expensive. If so, override all four.
Hashableproduces a hash; needed for Dict keys and Set elementshashlib/hash.mojo
KeyElement = Hashable + Equatable + Movable
| Signature | Remark |
|---|---|
__hash__(self, mut hasher: Some[Hasher]) | provided |
Hasherimplements a hash algorithm (the algorithm, not a hashable type)hashlib/hasher.mojo
| Signature | Remark |
|---|---|
__init__(out self) | |
_update_with_bytes(mut self, data: Span[Byte, _]) | |
_update_with_simd(mut self, value: SIMD[_,_]) | |
update(mut self, value: Some[Hashable]) | |
finish(var self) -> UInt64 |
Hashers remain alive after finalization. All three update methods are required.
Identifiableidentity; same-object test, enables is / is notbuiltin/identifiable.mojo
| Signature | Remark |
|---|---|
__is__(self, rhs: Self) -> Bool | |
__isnot__(self, rhs: Self) -> Bool | provided |
Excludes register-passable types, which don't have stable addresses.
Convert
Boolable, Intable, Floatableconvert with Bool(), Int(), Float64()builtin/bool.mojo · builtin/int.mojo · builtin/floatable.mojo
| Signature | Remark |
|---|---|
__bool__(self) -> Bool | Boolable |
__int__(self) -> Int | Intable |
__int__(self) raises -> Int | IntableRaising |
__float__(self) -> Float64 | Floatable |
__float__(self) raises -> Float64 | FloatableRaising |
If the method raises, use the Raising variant.
Boolable unlocks if / while / and / or usage.
Math
Absable, Powable, Roundableunary math operatorsmath/math.mojo
| Signature | Remark |
|---|---|
__abs__(self) -> Self | Absable · abs() |
__pow__(self, exp: Self) -> Self | Powable · pow(), ** |
__round__(self) -> Self | Roundable · round() |
__round__(self, ndigits: Int) -> Self | Roundable · round(), precision |
Ceilable, Floorable, Truncableround toward a boundmath/math.mojo
| Signature | Remark |
|---|---|
__ceil__(self) -> Self | Ceilable · ceil() |
__floor__(self) -> Self | Floorable · floor() |
__trunc__(self) -> Self | Truncable · trunc() |
CeilDivable, CeilDivableRaisingceiling division (rounds up instead of down)math/math.mojo
| Signature | Remark |
|---|---|
__ceildiv__(self, denominator: Self) -> Self | CeilDivable |
__ceildiv__(self, denominator: Self) raises -> Self | CeilDivableRaising |
DivModablecombined division and modulo; enables divmod()math/math.mojo
Refines: ImplicitlyCopyable < Copyable < Movable
| Signature | Remark |
|---|---|
__divmod__(self, denominator: Self) -> Tuple[Self, Self] |
Math outlier. The tuple is (quotient, remainder).
Iterate
Sized, SizedRaisinghas a length; enables len()builtin/len.mojo
| Signature | Remark |
|---|---|
__len__(self) -> Int | Sized |
__len__(self) raises -> Int | SizedRaising |
Iterableiterate by borrowingiter/__init__.mojo
| Signature | Remark |
|---|---|
IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]]: Iterator | associated type |
__iter__(ref self) -> Self.IteratorType[origin_of(self)] |
Parameterized on mutability and origin. Yields references tied to the source lifetime.
IterableOwnediterate by consuming and owningiter/__init__.mojo
| Signature | Remark |
|---|---|
IteratorOwnedType: Iterator | associated type |
__iter__(var self) -> Self.IteratorOwnedType |
No origin tracking.
Iteratorproduces elements one at a time; the for-loop workhorseiter/__init__.mojo
Refines: Deinitable, Movable
| Signature | Remark |
|---|---|
Element: Movable | associated type |
__next__(mut self) raises StopIteration -> Self.Element | |
bounds(self) -> Tuple[Int, Optional[Int]] | provided |
nth(var self, n: Int) -> Optional[Self.Element] | provided |
Requires an Iterable on the collection, and Iterator on the iterator. Don't rely on bounds() for safety checks. It's a hint.
Typed raises (StopIteration).
Interop
PathLikerepresents a file system pathos/pathlike.mojo
Path conforms
| Signature | Remark |
|---|---|
__fspath__(self) -> String |
ConvertibleToPythoncan be sent to Pythonpython/conversions.mojo
Refines: Deinitable
| Signature | Remark |
|---|---|
to_python_object(var self) raises -> PythonObject |
ConvertibleFromPythoncan be created from a Python objectpython/conversions.mojo
Refines: Copyable < Movable, Deinitable
| Signature | Remark |
|---|---|
__init__(out self, *, py: PythonObject) raises |