Fieldwise initialization in Mojo
@fieldwise_init writes the constructor for you, one argument per field in order.
@fieldwise_init
struct Color(ImplicitlyCopyable, Movable):
var red: Int
var green: Int
var blue: Int
def brightness(self) -> Int:
return (self.red + self.green + self.blue) // 3
def main():
var teal = Color(0, 128, 128)
print(teal.red, teal.green, teal.blue)
print(teal.brightness())
How it works
- The decorator generates
__init__takingred,green, andblue. brightnessaverages the three channels with floor division.Color(0, 128, 128)calls the generated constructor positionally.
Keywords and builtins used here
IntMovablebrightnessdefmainprintreturnselfstructvar
The run, in numbers
- Lines
- 14
- Characters to type
- 286
- Tokens
- 80
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 60 seconds.
Step 3 of 5 in A first struct, step 3 of 22 in Structs & traits.