typestar

Structs holding structs in Mojo

A struct field can be another struct, and the whole thing stays one flat value.

@fieldwise_init
struct Address(ImplicitlyCopyable, Movable):
    var city: String
    var zip_code: String


@fieldwise_init
struct Person(ImplicitlyCopyable, Movable):
    var name: String
    var home: Address

    def label(self) -> String:
        return self.name + " of " + self.home.city


def main():
    var home = Address("Austin", "78701")
    var ada = Person("Ada", home)
    print(ada.label(), ada.home.zip_code)

How it works

  1. Address gathers a city and a zip_code.
  2. Person stores an Address in its home field, nesting one struct in another.
  3. ada.home.zip_code walks both levels with a chain of dots.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
386
Tokens
94
Three-star pace
80 tpm

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

Type this snippet

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

← Previous Next →