typestar

A struct and its fields in Mojo

A struct is a named bundle of fields with a fixed layout the compiler knows exactly.

struct Planet(ImplicitlyCopyable, Movable):
    var name: String
    var moons: Int

    def __init__(out self, name: String, moons: Int):
        self.name = name
        self.moons = moons


def main():
    var earth = Planet("Earth", 1)
    var mars = Planet("Mars", 2)
    print(earth.name, earth.moons)
    print(mars.name, mars.moons)

How it works

  1. var name: String and var moons: Int declare the stored fields.
  2. __init__(out self, ...) fills every field before the struct is usable.
  3. Two Planet values are built and their fields read back with a dot.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
296
Tokens
84
Three-star pace
85 tpm

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

Type this snippet

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

Next →