typestar

Adding with __add__ in Mojo

Implement __add__ and the + operator starts working on your own type.

@fieldwise_init
struct Money(ImplicitlyCopyable, Movable):
    var cents: Int

    def __add__(self, other: Self) -> Self:
        return Money(self.cents + other.cents)


def main():
    var lunch = Money(1250)
    var coffee = Money(375)
    var total = lunch + coffee
    print(total.cents)

How it works

  1. Money stores a whole number of cents to dodge float rounding.
  2. __add__(self, other: Self) -> Self returns a fresh Money, leaving both inputs alone.
  3. lunch + coffee dispatches to that method.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
261
Tokens
65
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 46 seconds.

Type this snippet

Step 1 of 5 in Operators, step 11 of 22 in Structs & traits.

← Previous Next →