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
Moneystores a whole number ofcentsto dodge float rounding.__add__(self, other: Self) -> Selfreturns a freshMoney, leaving both inputs alone.lunch + coffeedispatches to that method.
Keywords and builtins used here
IntMovabledefmainprintreturnselfstructvar
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.
Step 1 of 5 in Operators, step 11 of 22 in Structs & traits.