Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Use Nested Structs in Go

Define a struct field using another struct type, initialize it with a keyed literal, and read or update its nested fields.

Table of Contents

Use a nested struct when a field has several related pieces of information. For example, declare an Address field on a Person and use person.Address.City to read the city.

Nested Structure in Golang Picture 1

Declare and initialize the nested field

package main

import "fmt"

type Address struct {
    City       string
    PostalCode string
}

type Person struct {
    Name    string
    Address Address
}

func main() {
    person := Person{
        Name: "Ava",
        Address: Address{
            City:       "Portland",
            PostalCode: "97201",
        },
    }
    fmt.Println(person.Address.City) // Portland
    person.Address.City = "Salem"
    fmt.Println(person.Address.City) // Salem
}

In Address Address, the first word is the field name and the second is its type. Use field names in the literal so a reader can tell which values belong to which fields. Keep postal codes as strings if they can start with a zero.

Choose a named field or an embedded field

A named field, as above, keeps access explicit. If you write just Address inside Person, you embed the type and Go may promote its fields, allowing a selector such as person.City. Use a pointer only if absence or sharing is meaningful. A value field has an empty Address as its zero value, while an uninitialized pointer is nil. See the Go specification for struct types.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.