typestar

Static methods as constructors in Mojo

@staticmethod gives a struct named constructors that read better than raw arguments.

@fieldwise_init
struct Temperature(ImplicitlyCopyable, Movable):
    var celsius: Float64

    @staticmethod
    def freezing() -> Temperature:
        return Temperature(0.0)

    @staticmethod
    def from_fahrenheit(degrees: Float64) -> Temperature:
        return Temperature((degrees - 32.0) * 5.0 / 9.0)


def main():
    var boiling = Temperature.from_fahrenheit(212.0)
    print(Temperature.freezing().celsius, boiling.celsius)

How it works

  1. freezing takes no self and hands back a fixed Temperature.
  2. from_fahrenheit converts before building, hiding the arithmetic.
  3. Both are called on the type itself: Temperature.freezing().

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
391
Tokens
74
Three-star pace
80 tpm

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

Type this snippet

Step 5 of 5 in A first struct, step 5 of 22 in Structs & traits.

← Previous Next →