typestar

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

  1. The decorator generates __init__ taking red, green, and blue.
  2. brightness averages the three channels with floor division.
  3. Color(0, 128, 128) calls the generated constructor positionally.

Keywords and builtins used here

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.

Type this snippet

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

← Previous Next →