Mojo Operator Overloading
Operator overloading means teaching an operator like + what to do with your own type. When you write a + b and a is a struct, Mojo looks for a method called __add__ on it. Write that method and + works. It’s the same idea as in Python, and the method names are the same. A few details differ, like how += works, and this page points them out.
Adding two values: __add__
Section titled “Adding two values: __add__”Here’s a 2D vector, the kind you’d use for positions or speeds in a game:
@fieldwise_initstruct Vec2(Writable): var x: Float64 var y: Float64
def __add__(self, other: Self) -> Self: return Self(self.x + other.x, self.y + other.y)
def __sub__(self, other: Self) -> Self: return Self(self.x - other.x, self.y - other.y)
def main(): var pos = Vec2(1.0, 2.0) var step = Vec2(0.5, -1.0) print(pos + step) print(pos - step) print(pos + step + step)Output:
Vec2(x=1.5, y=1.0)Vec2(x=0.5, y=3.0)Vec2(x=2.0, y=0.0)pos + step becomes pos.__add__(step). The method reads both vectors and returns a new one; it doesn’t change pos or step, so neither needs mut. That’s what people expect from +, and it’s why pos + step + step works: each + makes a fresh Vec2 for the next one. (Writable is only there so print can show a Vec2; see Printing Your Types.)
Which method goes with which operator
Section titled “Which method goes with which operator”| Operator | Method | Operator | Method |
|---|---|---|---|
a + b |
__add__ |
-a |
__neg__ |
a - b |
__sub__ |
+a |
__pos__ |
a * b |
__mul__ |
~a |
__invert__ |
a / b |
__truediv__ |
a & b |
__and__ |
a // b |
__floordiv__ |
a | b |
__or__ |
a % b |
__mod__ |
a ^ b |
__xor__ |
a ** b |
__pow__ |
a << b |
__lshift__ |
a @ b |
__matmul__ |
a >> b |
__rshift__ |
Each one is a normal method you write yourself. Mojo doesn’t create any of them for you. The comparison operators (==, < and friends) are special methods too, covered in Special Methods.
One-value operators: __neg__
Section titled “One-value operators: __neg__”Some operators take just one value. -v calls v.__neg__(), which takes only self:
@fieldwise_initstruct Vec2(Writable): var x: Float64 var y: Float64
def __neg__(self) -> Self: return Self(-self.x, -self.y)
def main(): var v = Vec2(3.0, -4.0) print(-v)Output:
Vec2(x=-3.0, y=4.0)Mixing types: v * 2.0
Section titled “Mixing types: v * 2.0”The argument of an operator method doesn’t have to be the same type. To scale a vector by a number, take a Float64. You can even write two __mul__ methods with different argument types, and Mojo picks the one that fits, just like with overloaded functions:
@fieldwise_initstruct Vec2(Writable): var x: Float64 var y: Float64
def __mul__(self, k: Float64) -> Self: return Self(self.x * k, self.y * k)
def __mul__(self, other: Self) -> Self: return Self(self.x * other.x, self.y * other.y)
def main(): var v = Vec2(1.0, 2.0) print(v * 3) print(v * 0.5) print(v * Vec2(10.0, 100.0))Output:
Vec2(x=3.0, y=6.0)Vec2(x=0.5, y=1.0)Vec2(x=10.0, y=200.0)The literal 3 turns into a Float64 without trouble. An Int variable doesn’t, though: with var n = 2, v * n fails with “value passed to ‘k’ cannot be converted from ‘Int’ to ‘Float64’”. Write v * Float64(n), as you learned in Type Conversion.
Number on the left: __rmul__
Section titled “Number on the left: __rmul__”v * 2.0 works now. What about 2.0 * v?
@fieldwise_initstruct Vec2(Writable): var x: Float64 var y: Float64
def __mul__(self, k: Float64) -> Self: return Self(self.x * k, self.y * k)
def main(): var v = Vec2(1.0, 2.0) print(2.0 * v)hello.mojo:11:17: error: no matching method in call to '__mul__' print(2.0 * v) ~~~~~~^mojo: error: failed to parse the provided Mojo source moduleMojo tried 2.0.__mul__(v) first, and the float doesn’t know anything about your Vec2. When that fails, Mojo tries a reversed method on the right-hand value: v.__rmul__(2.0). So add __rmul__:
@fieldwise_initstruct Vec2(Writable): var x: Float64 var y: Float64
def __mul__(self, k: Float64) -> Self: return Self(self.x * k, self.y * k)
def __rmul__(self, k: Float64) -> Self: return self * k
def main(): var v = Vec2(1.0, 2.0) print(2.0 * v) print(v * 2.0)Output:
Vec2(x=2.0, y=4.0)Vec2(x=2.0, y=4.0)__rmul__ just reuses __mul__, because the order doesn’t matter for scaling. For operators where order matters, like - or /, write __rsub__ and __rtruediv__ carefully: in 10.0 - v, self is v and the argument is 10.0.
Changing in place: += needs __iadd__
Section titled “Changing in place: += needs __iadd__”In Python, if a class has __add__ but no __iadd__, a += b quietly becomes a = a + b. Mojo doesn’t do that:
@fieldwise_initstruct Money: var cents: Int
def __add__(self, other: Self) -> Self: return Self(self.cents + other.cents)
def main(): var total = Money(100) total += Money(250) print(total.cents)hello.mojo:10:11: error: 'Money' does not implement the '__iadd__' method total += Money(250) ~~~~~ ^mojo: error: failed to parse the provided Mojo source moduleYou can write total = total + Money(250) instead, or add __iadd__. It changes self instead of returning a new value, so it takes mut self and returns nothing:
@fieldwise_initstruct Money: var cents: Int
def __add__(self, other: Self) -> Self: return Self(self.cents + other.cents)
def __iadd__(mut self, other: Self): self.cents += other.cents
def main(): var total = Money(100) total += Money(250) total += Money(5) print(total.cents)Output:
355The other in-place operators follow the same pattern: -= calls __isub__, *= calls __imul__, and so on.
Putting it together
Section titled “Putting it together”Here’s a small Money type with the operators that make sense for money, used to add up a shopping list:
@fieldwise_initstruct Money(Comparable, Copyable, Writable): var cents: Int
def __add__(self, other: Self) -> Self: return Self(self.cents + other.cents)
def __iadd__(mut self, other: Self): self.cents += other.cents
def __mul__(self, count: Int) -> Self: return Self(self.cents * count)
def __lt__(self, other: Self) -> Bool: return self.cents < other.cents
def main(): var total = Money(0) total += Money(250) * 2 total += Money(1999) print(total) var budget = Money(2500) if budget < total: print("over budget") else: print("fits the budget")Output:
Money(cents=2499)fits the budgetStoring money as whole cents in an Int avoids rounding surprises you’d get with floats. Notice what’s not there: there’s no __mul__ that takes another Money, because “dollars times dollars” doesn’t mean anything. Only add operators that have an obvious meaning for your type. The official guide to adding operator support to custom types builds a full complex-number type the same way.
Practice
Section titled “Practice”1. Adding fractions
Section titled “1. Adding fractions”Make a Fraction struct with num and den (both Int). Add __add__ using a/b + c/d = (a*d + c*b) / (b*d), then print 1/2 + 1/3 as 5 / 6.
Hint: return Self(...) with the new numerator and denominator, and print the two fields.
Show solution
@fieldwise_initstruct Fraction: var num: Int var den: Int
def __add__(self, other: Self) -> Self: return Self(self.num * other.den + other.num * self.den, self.den * other.den)
def main(): var f = Fraction(1, 2) + Fraction(1, 3) print(f.num, "/", f.den)Output:
5 / 6The result isn’t simplified (2/4 + 1/4 would give 12/16). Adding a greatest-common-divisor step is a nice extra exercise.
2. Counting down
Section titled “2. Counting down”Give this Timer struct a -= operator so the program prints 45.
@fieldwise_initstruct Timer: var seconds: Int
def main(): var t = Timer(60) t -= 15 print(t.seconds)Hint: -= calls __isub__, which takes mut self. The right-hand side here is an Int, not a Timer.
Show solution
@fieldwise_initstruct Timer: var seconds: Int
def __isub__(mut self, amount: Int): self.seconds -= amount
def main(): var t = Timer(60) t -= 15 print(t.seconds)Output:
45The argument type is up to you. Taking an Int means you can subtract plain numbers of seconds.
a + bcallsa.__add__(b); every operator maps to a method with a fixed name.- Operator methods usually take a read-only
selfand return a new value. - The argument can be another type, and you can overload the same operator for several types.
- When the left value doesn’t know your type (
2.0 * v), Mojo tries the reversed method:__rmul__,__radd__and so on. +=needs__iadd__(withmut self); Mojo doesn’t fall back to__add__like Python does.- Only overload operators whose meaning is obvious for your type.
Next up: printing your types, making print() and t-strings show your structs the way you want.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Add operator support to custom types: the official walkthrough of forward, reversed and in-place methods.
- Mojo operators: every operator in the language, with precedence.
- Mojo structs: special methods: how operator methods fit with the other special methods.
- Python’s data model: emulating numeric types: the Python version, if you want to compare.