Skip to content

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.

Here’s a 2D vector, the kind you’d use for positions or speeds in a game:

@fieldwise_init
struct 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.)

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.

Some operators take just one value. -v calls v.__neg__(), which takes only self:

@fieldwise_init
struct 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)

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_init
struct 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.

v * 2.0 works now. What about 2.0 * v?

@fieldwise_init
struct 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 module

Mojo 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_init
struct 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.

In Python, if a class has __add__ but no __iadd__, a += b quietly becomes a = a + b. Mojo doesn’t do that:

@fieldwise_init
struct 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 module

You 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_init
struct 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:

355

The other in-place operators follow the same pattern: -= calls __isub__, *= calls __imul__, and so on.

Here’s a small Money type with the operators that make sense for money, used to add up a shopping list:

@fieldwise_init
struct 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 budget

Storing 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.

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_init
struct 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 / 6

The result isn’t simplified (2/4 + 1/4 would give 12/16). Adding a greatest-common-divisor step is a nice extra exercise.

Give this Timer struct a -= operator so the program prints 45.

@fieldwise_init
struct 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_init
struct 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:

45

The argument type is up to you. Taking an Int means you can subtract plain numbers of seconds.

  • a + b calls a.__add__(b); every operator maps to a method with a fixed name.
  • Operator methods usually take a read-only self and 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__ (with mut 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

1. Which method does a * b call when a is your struct?
2. Your Vec2 has __mul__(self, k: Float64). Why does 2.0 * v still fail?
3. A struct has __add__ but no __iadd__. What happens with total += x?
4. What should __add__ usually do?