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
Addressgathers acityand azip_code.Personstores anAddressin itshomefield, nesting one struct in another.ada.home.zip_codewalks both levels with a chain of dots.
Keywords and builtins used here
MovableStringdeflabelmainprintreturnselfstructvar
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.
Step 4 of 5 in A first struct, step 4 of 22 in Structs & traits.