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
freezingtakes noselfand hands back a fixedTemperature.from_fahrenheitconverts before building, hiding the arithmetic.- Both are called on the type itself:
Temperature.freezing().
Keywords and builtins used here
Float64Movabledeffreezingfrom_fahrenheitmainprintreturnstructvar
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.
Step 5 of 5 in A first struct, step 5 of 22 in Structs & traits.