×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Structures

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Nested Structures

Last Updated : July 22, 2025

In Go, nested structures refer to the concept of defining one struct type within another.

Defining Nested Structures

You can nest one struct inside another by declaring a struct as a field within another struct.

Example

The following example demonstrates how to define and use a nested struct in Go:

package main
import "fmt"

type Address struct {
    city    string
    pincode int
}

type Employee struct {
    name    string
    age     int
    address Address
}

func main() {
    emp := Employee{
        name: "Raj",
        age:  28,
        address: Address{
            city:    "Mumbai",
            pincode: 400001,
        },
    }

    fmt.Println("Name:", emp.name)
    fmt.Println("City:", emp.address.city)
    fmt.Println("Pincode:", emp.address.pincode)
}

When you run the above code, the output will be:

Name: Raj
City: Mumbai
Pincode: 400001

Anonymous Nested Struct

You can also define anonymous nested structs within another struct without creating a named type for the inner struct.

Example

The following example demonstrates how to define and access a nested structure in Go, where one structure is embedded within another:

package main
import "fmt"

type Student struct {
    name string
    marks struct {
        maths    int
        science  int
    }
}

func main() {
    var s Student
    s.name = "Sneha"
    s.marks.maths = 85
    s.marks.science = 90

    fmt.Println("Name:", s.name)
    fmt.Println("Maths Marks:", s.marks.maths)
    fmt.Println("Science Marks:", s.marks.science)
}

When you run the above code, the output will be:

Name: Sneha
Maths Marks: 85
Science Marks: 90

Go Nested Structures Exercise

Select the correct option to complete each statement about nested structures in Go.

  1. To access the city field of a nested Address struct inside Employee, you should use:
  2. In Go, what is a nested struct?
  3. Anonymous structs inside another struct can be used to:

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.