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.
The short list
Section titled “The short list”| 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.
Movable: every struct can move
Section titled “Movable: every struct can move”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_initstruct Ticket: var seat: String
def main(): var mine = Ticket("12A") var yours = mine^ print(yours.seat)Output:
12AAfter 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.
Copyable: copies on request
Section titled “Copyable: copies on request”A plain struct can’t be copied at all. Even calling .copy() fails:
@fieldwise_initstruct 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 moduleAdd Copyable and Mojo writes the copy code for you, copying each field:
@fieldwise_initstruct 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.
ImplicitlyCopyable: copies without asking
Section titled “ImplicitlyCopyable: copies without asking”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_initstruct 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_initstruct 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 moduleA 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.
Equatable and Comparable
Section titled “Equatable and Comparable”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_initstruct 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)Truemin uses your __lt__ (the fastest runner wins), while == still compares both fields.
Hashable: Dict keys and Set elements
Section titled “Hashable: Dict keys and Set elements”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_initstruct 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:
2True FalsetreasureCell(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 Setfrom std.hash import Hasher
@fieldwise_initstruct 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]() 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)0Int 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.
Names you might see in older code
Section titled “Names you might see in older code”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.
Practice
Section titled “Practice”1. A copyable recipe
Section titled “1. A copyable recipe”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_initstruct 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_initstruct 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 3Copyable makes Mojo write a copy that copies each field, including the whole list, so the two recipes don’t share steps.
2. Count unique colors
Section titled “2. Count unique colors”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_initstruct 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:
2The 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. Copyableadds.copy();ImplicitlyCopyablealso allows plainvar b = a, for small, cheap types only.Equatable,WritableandHashablewrite field-by-field methods for you when every field has the trait.Comparableneeds just__lt__and gives you sorting,minandmax.Dictkeys andSetelements needHashable+Equatable; if you write__eq__, write a matching__hash__.- Old names like
@value,Stringableand@register_passableare gone in Mojo 1.2.
Next up: context managers, using with to make sure cleanup code always runs.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo traits cheat sheet: every standard trait, what it requires and what it provides.
- Making a struct copyable: the manual’s section on
CopyableandImplicitlyCopyable. Hashable: the default hash and the rule that equal values need equal hashes.Copyable: the copy initializer and thecopy()method.- Value lifecycle: how Mojo creates, copies, moves and destroys values.