0
0
Goprogramming~5 mins

Nested structs in Go

Choose your learning style9 modes available
Introduction
Nested structs help organize related information inside other information, like putting a smaller box inside a bigger box.
When you want to group related details inside a bigger object, like an address inside a person.
When you want to keep your data organized and easy to understand.
When you want to reuse smaller structs inside bigger ones without repeating code.
Syntax
Go
type Inner struct {
    Field1 string
    Field2 int
}

type Outer struct {
    InnerField Inner
}
You define the smaller struct first, then use it inside the bigger struct.
You access nested fields using dot notation, like Outer.InnerField.Field1.
Examples
A Person struct has a nested Address struct to store city and zip code.
Go
type Address struct {
    City string
    ZipCode int
}

type Person struct {
    Name string
    Age int
    Home Address
}
A Car struct contains an Engine struct to describe its engine details.
Go
type Engine struct {
    Horsepower int
}

type Car struct {
    Brand string
    Engine Engine
}
Sample Program
This program creates a Person with a nested Address. It prints all details using dot notation.
Go
package main

import "fmt"

type Address struct {
    City    string
    ZipCode int
}

type Person struct {
    Name string
    Age  int
    Home Address
}

func main() {
    p := Person{
        Name: "Alice",
        Age:  30,
        Home: Address{
            City:    "Wonderland",
            ZipCode: 12345,
        },
    }

    fmt.Println("Name:", p.Name)
    fmt.Println("Age:", p.Age)
    fmt.Println("City:", p.Home.City)
    fmt.Println("Zip Code:", p.Home.ZipCode)
}
OutputSuccess
Important Notes
You can nest structs as many levels as you want, but keep it simple to avoid confusion.
Use clear names for nested structs to make your code easy to read.
Remember to initialize nested structs before using their fields.
Summary
Nested structs let you put one struct inside another to organize data.
Access nested fields using dot notation, like Outer.Inner.Field.
They help keep your code clean and your data grouped logically.