Bird
Raised Fist0
Goprogramming~10 mins

Nested structs in Go - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Nested structs
Define Outer Struct
↓
Define Inner Struct
↓
Create Outer Struct Instance
↓
Assign Inner Struct to Outer
↓
Access Inner Struct Fields
↓
Use Nested Data
This flow shows how to define a struct inside another struct, create instances, assign values, and access nested fields.
Execution Sample
Go
package main

import "fmt"

type Address struct {
    City string
    Zip  int
}

type Person struct {
    Name    string
    Address Address
}

func main() {
    p := Person{Name: "Alice", Address: Address{City: "NYC", Zip: 10001}}
    fmt.Println(p.Name, p.Address.City, p.Address.Zip)
}
This code defines two structs, Person and Address, nests Address inside Person, creates a Person instance, and prints nested fields.
Execution Table
StepActionVariable/FieldValueNotes
1Define struct AddressAddressstruct with City(string), Zip(int)Struct type created
2Define struct PersonPersonstruct with Name(string), Address(Address)Struct type created with nested struct
3Create Person instance pp.Name"Alice"Name field set
3Create Person instance pp.Address.City"NYC"Nested City field set
3Create Person instance pp.Address.Zip10001Nested Zip field set
4Print p.NameOutput"Alice"Access outer struct field
4Print p.Address.CityOutput"NYC"Access nested struct field
4Print p.Address.ZipOutput10001Access nested struct field
5End of main--Program ends
💡 Program ends after printing nested struct fields
Variable Tracker
VariableStartAfter Step 3Final
p.Name"""Alice""Alice"
p.Address.City"""NYC""NYC"
p.Address.Zip01000110001
Key Moments - 2 Insights
Why do we write p.Address.City instead of just p.City?
Because City is inside the nested Address struct, so we must access it through p.Address as shown in execution_table rows 4-7.
Can we assign Address fields directly without creating Address struct first?
No, we must create the Address struct instance first and assign it to p.Address, as shown in step 3 of execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of p.Address.Zip after step 3?
A10001
B0
C"NYC"
D"Alice"
💡 Hint
Check execution_table row 5 where p.Address.Zip is set to 10001
At which step do we assign the Name field of p?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at execution_table row 3 where p.Name is set to "Alice"
If we tried to print p.City directly, what would happen?
AIt prints the city name
BIt prints empty string
CCompilation error: p.City undefined
DIt prints zero
💡 Hint
Refer to key_moments question 1 about accessing nested fields
Concept Snapshot
Nested structs in Go:
- Define inner struct type
- Use inner struct as field in outer struct
- Create outer struct instance with inner struct values
- Access nested fields with dot notation (outer.inner.field)
- Nested structs group related data clearly
Full Transcript
This example shows how to use nested structs in Go. First, we define an Address struct with City and Zip fields. Then, we define a Person struct that includes a Name and an Address field. We create a Person instance named p, setting Name to "Alice" and Address to an Address instance with City "NYC" and Zip 10001. We print p.Name, p.Address.City, and p.Address.Zip. The execution table traces each step, showing how fields are assigned and accessed. Key points include accessing nested fields with p.Address.City and the need to create the nested struct instance before assigning it. The quiz checks understanding of these steps. This helps organize complex data clearly in Go programs.

Practice

(1/5)
1. What is the main purpose of using nested structs in Go?
easy
A. To group related data together inside another struct
B. To create multiple independent structs
C. To make the program run faster
D. To avoid using functions

Solution

  1. Step 1: Understand struct grouping

    Nested structs allow one struct to contain another, grouping related data logically.
  2. Step 2: Compare options

    Creating multiple independent structs, making the program run faster, or avoiding functions do not describe grouping data inside structs.
  3. Final Answer:

    To group related data together inside another struct -> Option A
  4. Quick Check:

    Nested structs = Group related data [OK]
Hint: Think of nested structs as folders inside folders [OK]
Common Mistakes:
  • Confusing nested structs with separate structs
  • Thinking nested structs improve speed
  • Believing nested structs replace functions
2. Which of the following is the correct way to access the field City inside a nested struct Address within struct Person?
easy
A. person.City.Address
B. person->Address->City
C. person.Address.City
D. person.Address->City

Solution

  1. Step 1: Recall Go syntax for nested structs

    Access nested fields using dot notation: Outer.Inner.Field.
  2. Step 2: Evaluate options

    person.Address.City uses correct dot notation. Arrow syntax (->) is invalid in Go. person.City.Address reverses the order.
  3. Final Answer:

    person.Address.City -> Option C
  4. Quick Check:

    Dot notation = person.Address.City [OK]
Hint: Use dot notation to access nested fields [OK]
Common Mistakes:
  • Using arrow (->) instead of dot (.)
  • Reversing the order of fields
  • Trying to access nested fields directly without parent
3. What will be the output of the following Go code?
package main
import "fmt"
type Address struct {
    City string
    Zip  int
}
type Person struct {
    Name    string
    Address Address
}
func main() {
    p := Person{Name: "Anna", Address: Address{City: "Paris", Zip: 75000}}
    fmt.Println(p.Address.City)
}
medium
A. Anna
B. Paris
C. 75000
D. Address

Solution

  1. Step 1: Understand struct initialization

    Person struct has Name and Address fields. Address is initialized with City "Paris" and Zip 75000.
  2. Step 2: Identify printed field

    The code prints p.Address.City, which is "Paris".
  3. Final Answer:

    Paris -> Option B
  4. Quick Check:

    p.Address.City = Paris [OK]
Hint: Print nested field with dot notation [OK]
Common Mistakes:
  • Printing the wrong field like Name or Zip
  • Confusing struct field names
  • Expecting the whole struct to print
4. Identify the error in this Go code snippet involving nested structs:
package main
import "fmt"
type Engine struct {
    Power int
}
type Car struct {
    Model  string
    Engine Engine
}
func main() {
    c := Car{Model: "Sedan"}
    fmt.Println(c.Engine.Power)
}
medium
A. c.Engine.Power is zero value, no error
B. Car struct missing Engine field
C. Engine struct is not defined
D. Cannot print nested struct fields directly

Solution

  1. Step 1: Check struct definitions

    Engine and Car structs are defined correctly. Car has Engine field.
  2. Step 2: Analyze initialization and print

    Car instance c is created with Model only. Engine field is zero-valued (Power = 0). Printing c.Engine.Power prints 0 without error.
  3. Final Answer:

    c.Engine.Power is zero value, no error -> Option A
  4. Quick Check:

    Uninitialized nested struct fields have zero values [OK]
Hint: Uninitialized nested structs have zero values [OK]
Common Mistakes:
  • Assuming missing initialization causes error
  • Thinking nested fields can't be printed
  • Confusing missing fields with zero values
5. Given the structs below, how would you write a function FullAddress that returns a formatted string combining Street, City, and Zip from nested structs?
type Location struct {
    Street string
    City   string
}
type Address struct {
    Location Location
    Zip      int
}
hard
A. func FullAddress(a Address) string { return a.Street + ", " + a.City + " " + fmt.Sprint(a.Zip) }
B. func FullAddress(a Address) string { return a.Street + ", " + a.Location.City + " " + fmt.Sprint(a.Zip) }
C. func FullAddress(a Address) string { return a.Location.Street + ", " + a.City + " " + fmt.Sprint(a.Zip) }
D. func FullAddress(a Address) string { return a.Location.Street + ", " + a.Location.City + " " + fmt.Sprint(a.Zip) }

Solution

  1. Step 1: Identify nested fields

    Street and City are inside Location struct, which is nested inside Address.
  2. Step 2: Access nested fields correctly

    Use a.Location.Street and a.Location.City to access those fields, and a.Zip for Zip code.
  3. Step 3: Check options

    Only func FullAddress(a Address) string { return a.Location.Street + ", " + a.Location.City + " " + fmt.Sprint(a.Zip) } correctly accesses nested fields with dot notation.
  4. Final Answer:

    func FullAddress(a Address) string { return a.Location.Street + ", " + a.Location.City + " " + fmt.Sprint(a.Zip) } -> Option D
  5. Quick Check:

    Access nested fields with dot notation [OK]
Hint: Use dot notation for each nested level [OK]
Common Mistakes:
  • Accessing nested fields directly without parent struct
  • Mixing field names from different structs
  • Forgetting to convert int Zip to string
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard