Skip to content

Mojo Common Traits

The standard library comes with traits that plug your structs into the language: copying, ==, sorting, printing, using them as Dict keys. You’ve met several of them in the last few lessons. This page puts them side by side, shows what each one gives you, and points out the ones that Mojo writes for you, so you know which methods you actually have to write. All of these traits are in the prelude, so you never import them.

Trait What it lets you do Do you write a method?
Movable Move a value with ^ No, every struct has it
Copyable Copy with .copy() No, if all fields are Copyable
ImplicitlyCopyable Copy with plain var b = a No, if all fields are implicitly copyable
Writable print, String(), t-strings Optional write_to
Equatable == and != Optional __eq__
Comparable <, >, <=, >=, sort, min, max __lt__
Hashable Be a Dict key or Set element (with Equatable) Optional __hash__
Boolable, Sized Bool(x), if x:, len(x) __bool__, __len__
Intable, Floatable Int(x), Float64(x) __int__, __float__
Defaultable Create with no arguments in generic code __init__(out self)

“Optional” means Mojo writes a field-by-field version for you if you don’t. That works as long as every field already has the trait. The traits cheat sheet has the full list, including rarer ones like Absable and Iterable.

Moving a value hands it from one variable to another. You do it with the ^ operator, and the old variable can’t be used afterwards. Every struct is Movable without you asking:

@fieldwise_init
struct Ticket:
var seat: String
def main():
var mine = Ticket("12A")
var yours = mine^
print(yours.seat)

Output:

12A

After mine^, the ticket belongs to yours. Using mine again would give “use of uninitialized value ‘mine’”. There’s only ever one ticket, so a move is cheap: nothing is duplicated. The Moving Values lesson covers ^ in depth.

A plain struct can’t be copied at all. Even calling .copy() fails:

@fieldwise_init
struct Team:
var name: String
def main():
var a = Team("Reds")
var b = a.copy()
print(b.name)
hello.mojo:7:14: error: 'Team' value has no attribute 'copy'
var b = a.copy()
~^
mojo: error: failed to parse the provided Mojo source module

Add Copyable and Mojo writes the copy code for you, copying each field:

@fieldwise_init
struct Team(Copyable, Writable):
var name: String
var players: List[String]
def main():
var a = Team("Reds", ["Ann", "Bo"])
var b = a.copy()
b.players.append("Cy")
print(a)
print(b)

Output:

Team(name=Reds, players=[Ann, Bo])
Team(name=Reds, players=[Ann, Bo, Cy])

b is a full, separate copy: adding a player to b leaves a alone. In Python, b = a would share one object and both would show Cy. Most structs that hold data should be Copyable. A List of your struct needs it for things like printing and sorting, and the error message usually suggests .copy() when you forget.

With Copyable, var b = a is still an error; you must write a.copy() (or move with a^). For small, cheap values you can allow plain = copies with ImplicitlyCopyable:

@fieldwise_init
struct Point(ImplicitlyCopyable, Writable):
var x: Int
var y: Int
def main():
var a = Point(1, 2)
var b = a
b.x = 99
print(a, b)

Output:

Point(x=1, y=2) Point(x=99, y=2)

ImplicitlyCopyable includes Copyable, so .copy() works too. Mojo won’t let you add it to a struct with an expensive field:

@fieldwise_init
struct Team(ImplicitlyCopyable):
var players: List[String]
def main():
var t = Team(["Ann"])
print(len(t.players))
hello.mojo:3:5: error: cannot synthesize implicit copy constructor because field 'players' has non-implicitly-copyable type 'List[String]'
var players: List[String]
^
mojo: error: failed to parse the provided Mojo source module

A List can hold millions of items, and Mojo doesn’t want that copied behind your back. So the rule of thumb is: ImplicitlyCopyable for small values made of numbers and strings (a point, a color, a date), Copyable for everything else.

You met these in Special Methods. As a reminder: Equatable gives you == and !=, comparing every field unless you write __eq__. Comparable needs one method, __lt__, and gives you the other three comparisons and ==. It also makes your type work with sort, min and max:

@fieldwise_init
struct Runner(Comparable, Copyable, Writable):
var name: String
var seconds: Int
def __lt__(self, other: Self) -> Bool:
return self.seconds < other.seconds
def main():
var a = Runner("Ann", 754)
var b = Runner("Bo", 731)
print(min(a, b))
print(a == Runner("Ann", 754))

Output:

Runner(name=Bo, seconds=731)
True

min uses your __lt__ (the fastest runner wins), while == still compares both fields.

A Dict key or a Set element has to be Hashable and Equatable. Without them, you get an error saying the type isn’t a KeyElement (Mojo’s name for “Equatable & Hashable & Movable”). With them, Mojo writes the hash for you from the fields:

from std.collections import Set
@fieldwise_init
struct Cell(Hashable, Equatable):
var row: Int
var col: Int
def main():
var visited = Set[Cell]()
visited.add(Cell(0, 0))
visited.add(Cell(0, 1))
visited.add(Cell(0, 0))
print(len(visited))
print(Cell(0, 1) in visited, Cell(5, 5) in visited)
var labels = Dict[Cell, String]()
labels[Cell(2, 3)] = "treasure"
print(labels.get(Cell(2, 3)).or_else("nothing"))

Output:

2
True False
treasure

Cell(0, 0) was added twice but counted once, because the two are equal and have the same hash.

If you write your own __eq__, write a matching __hash__ too. The rule is: values that are equal must have equal hashes. Here two emails are equal regardless of case, so the hash ignores case as well:

from std.collections import Set
from std.hash import Hasher
@fieldwise_init
struct Email(Hashable, Equatable):
var address: String
def __eq__(self, other: Self) -> Bool:
return self.address.lower() == other.address.lower()
def __hash__(self, mut hasher: Some[Hasher]):
hasher.update(self.address.lower().as_bytes())
def main():
var inbox = Set[Email]()
inbox.add(Email("[email protected]"))
inbox.add(Email("[email protected]"))
print(len(inbox))

Output:

1

__hash__ doesn’t return a number. It feeds bytes to a Hasher (from std.hash), which does the math. If you kept the automatic hash here, the two emails would be equal but hash differently, and the set could keep both.

Defaultable: building a value from nothing

Section titled “Defaultable: building a value from nothing”

Defaultable says “this type can be created with no arguments”. You need it when generic code has to make a fresh value without knowing the type:

struct Settings(Defaultable, Writable):
var retries: Int
var name: String
def __init__(out self):
self.retries = 3
self.name = "default"
def fresh[T: Defaultable]() -> T:
return T()
def main():
print(fresh[Settings]())
print(fresh[Int]())

Output:

Settings(retries=3, name=default)
0

Int is Defaultable too, and Int() is 0. In everyday code you’d just call Settings(); the trait matters when you write generic functions and containers.

Mojo’s traits were renamed and reorganized before 1.0. If you find these in a blog post or an old example, here’s what to use in 1.2:

Old name In Mojo 1.2
@value decorator @fieldwise_init plus Copyable (and Movable, which is automatic)
@register_passable("trivial") The TrivialRegisterPassable trait
Stringable, __str__ Writable and write_to
Representable, __repr__ Writable and write_repr_to
EqualityComparable Equatable

All the old names fail with “use of unknown declaration”, so they’re easy to spot.

This program doesn’t build. Make the Recipe struct copyable, so the program prints the original with 2 steps and the copy with 3.

@fieldwise_init
struct Recipe:
var name: String
var steps: List[String]
def main():
var soup = Recipe("soup", ["boil", "stir"])
var spicy = soup.copy()
spicy.steps.append("add chili")
print(len(soup.steps), len(spicy.steps))

Hint: which trait gives a struct the .copy() method? ImplicitlyCopyable won’t work here, because of the List field.

Show solution
@fieldwise_init
struct Recipe(Copyable):
var name: String
var steps: List[String]
def main():
var soup = Recipe("soup", ["boil", "stir"])
var spicy = soup.copy()
spicy.steps.append("add chili")
print(len(soup.steps), len(spicy.steps))

Output:

2 3

Copyable makes Mojo write a copy that copies each field, including the whole list, so the two recipes don’t share steps.

Make a Color struct with r, g and b (all Int) that can go in a Set. Add red, green and red again, then print how many unique colors there are.

Hint: Set needs Hashable and Equatable, and you import it with from std.collections import Set.

Show solution
from std.collections import Set
@fieldwise_init
struct Color(Hashable, Equatable):
var r: Int
var g: Int
var b: Int
def main():
var seen = Set[Color]()
seen.add(Color(255, 0, 0))
seen.add(Color(0, 255, 0))
seen.add(Color(255, 0, 0))
print(len(seen))

Output:

2

The automatic __eq__ and __hash__ both use all three fields, so the two reds count as one color.

  • Every struct is Movable: var b = a^ hands the value over.
  • Copyable adds .copy(); ImplicitlyCopyable also allows plain var b = a, for small, cheap types only.
  • Equatable, Writable and Hashable write field-by-field methods for you when every field has the trait.
  • Comparable needs just __lt__ and gives you sorting, min and max.
  • Dict keys and Set elements need Hashable + Equatable; if you write __eq__, write a matching __hash__.
  • Old names like @value, Stringable and @register_passable are gone in Mojo 1.2.

Next up: context managers, using with to make sure cleanup code always runs.

Quick check

1. A struct has a List[String] field. Which trait lets you copy it?
2. What does a struct need so it can be used as a Dict key?
3. You write a custom __eq__ that ignores upper and lower case. What else should you do?
4. What replaced the @value decorator from older Mojo code?