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
var name: Stringandvar moons: Intdeclare the stored fields.__init__(out self, ...)fills every field before the struct is usable.- Two
Planetvalues are built and their fields read back with a dot.
Keywords and builtins used here
IntMovableStringdefmainprintselfstructvar
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.
Step 1 of 5 in A first struct, step 1 of 22 in Structs & traits.