Back to Blog

Structs (Custom Data Types & Nested Structs) - Go Tutorial for Beginners #15

Sandy LaneSandy Lane

Video: Structs (Custom Data Types & Nested Structs) - Go Tutorial for Beginners #15 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Structs (Custom Data Types & Nested Structs) in Go

Structs in Go allow you to create custom data types by grouping related fields together. This tutorial covers defining structs, creating instances, modifying fields, nested structs, and using anonymous structs for quick, one-time data grouping.

Code

package main

import "fmt"

// Define a struct type named Person
type Person struct {
  Name string
  Age  int
  City string
}

// Define a nested struct type named Address
type Address struct {
  City   string
  Street string
  Zip    string
}

// Define a struct with a nested struct field
type Employee struct {
  Name    string
  Address Address  // Nested struct
}

func main() {
  // Create a Person instance using named fields (recommended)
  p := Person{Name: "Alice", Age: 25, City: "NYC"}

  // Access fields with dot notation
  fmt.Println("Name:", p.Name)  // Output: Alice

  // Modify a field
  p.Age = 26
  fmt.Println("Age:", p.Age)    // Output: 26

  // Create an Employee with a nested Address struct
  emp := Employee{
    Name: "Bob",
    Address: Address{
      City:   "San Francisco",
      Street: "Market St",
      Zip:    "94103",
    },
  }
  fmt.Println("Employee City:", emp.Address.City)  // Access nested field

  // Anonymous struct for one-time use
  config := struct {
    Host string
    Port int
  }{
    Host: "localhost",
    Port: 8080,
  }
  fmt.Println("Config Host:", config.Host)

  // Structs are copied by value
  copyPerson := p
  copyPerson.Name = "Charlie"
  fmt.Println("Original Name:", p.Name)    // Alice
  fmt.Println("Copy Name:", copyPerson.Name) // Charlie

  // Compare structs (all fields must be comparable)
  p2 := Person{Name: "Alice", Age: 26, City: "NYC"}
  fmt.Println("p == p2?", p == p2)  // true
}

Key Points

  • Structs group related fields into a single custom data type for better organization.
  • Named field initialization improves code readability and reduces errors compared to positional initialization.
  • Nested structs embed one struct inside another, allowing complex data structures.
  • Anonymous structs provide a quick way to define and use a struct without a formal type declaration.
  • Structs are copied by value, so assigning one struct to another creates an independent copy.