Truthiness with __bool__ in Mojo
__bool__ decides what your struct means inside an if.
@fieldwise_init
struct Cart(ImplicitlyCopyable, Movable):
var items: Int
def __bool__(self) -> Bool:
return self.items > 0
def main():
var cart = Cart(0)
if cart:
print("ready to check out")
else:
print("the cart is empty")
How it works
Cartcounts itsitems.__bool__reports true only when that count is above zero.if cart:calls the method, so an empty cart takes theelsebranch.
Keywords and builtins used here
IntMovabledefelseifmainprintreturnselfstructvar
The run, in numbers
- Lines
- 14
- Characters to type
- 226
- Tokens
- 54
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 38 seconds.
Step 4 of 5 in Operators, step 14 of 22 in Structs & traits.