ProgramGuru

Nested Structs

Start with Nested Structs

A struct field may itself be another struct, allowing you to model a larger object from smaller meaningful parts.

What you’ll learn

  • Explain the main purpose of nested structs.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Declare one named struct type, such as Address, then use it as a field inside Person. Read deeper fields with chained selectors like person.Home.City.

Nesting communicates ownership and structure. Because structs are values, copying a Person also copies any nested Address value fields, unless a nested field is itself a pointer or another storage-sharing type.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for nested structsEach selector moves one level into the nested struct.Person valueStep 1Home field: AddressStep 2City field: PuneStep 3Update CityStep 4Each selector moves one level into the nested struct.
Each selector moves one level into the nested struct.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

type Address struct {
	City string
	Pin  int
}
type Person struct {
	Name string
	Home Address
}

func main() {
	person := Person{Name: "Ava", Home: Address{City: "Pune", Pin: 411001}}
	fmt.Println("Name:", person.Name)
	fmt.Println("City:", person.Home.City)
	person.Home.City = "Mumbai"
	fmt.Println("New city:", person.Home.City)
}

Output

Name: Ava
City: Pune
New city: Mumbai

Trace what the program does

The Person literal contains a complete Address struct value in the Home field. Selectors reach the city, and assigning a new city updates only that nested field.

Avoid common mistakes

  • Nested field access uses the actual field names; names are not automatically flattened.
  • Copying the outer struct also copies ordinary nested struct fields.

Try it yourself

Add Country to Address and read it through person.Home.Country.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which expression reads a nested City field?
Choose one answer. You can try again.

Answer and explanation

person.Home.City

Correct. The Person literal contains a complete Address struct value in the Home field.

What you should remember

You have practiced Nested Structs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Anonymous Structs →