typestar

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

  1. Cart counts its items.
  2. __bool__ reports true only when that count is above zero.
  3. if cart: calls the method, so an empty cart takes the else branch.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 5 in Operators, step 14 of 22 in Structs & traits.

← Previous Next →