Version: 1.1.0

Creating values

A value begins in an initializer. Mojo generates the simple ones and lets you write the rest.

Essentials

  • __init__(out self) is the constructor. out means self starts uninitialized.
  • @fieldwise_init generates an initializer with one argument per field.
  • A copy initializer builds a value from an existing one.
  • Factory functions are ordinary functions that return the struct.
  • Every field must be initialized before the constructor returns.

Example

@fieldwise_init
struct Color:
    var r: Int
    var g: Int
    var b: Int

def main():
    var ink = Color(20, 20, 20)
    print(ink.r)

Keep in mind

Do not use a field before it has been stored. The compiler treats that read as uninitialized.