Structs in Go – Modeling Real-World Data

PrajwalPrajwal
3 min read

Learn how to use structs in Golang to represent real-world entities

In Golang, structs are used to model real-world entities — like a User, Book, or Product — by grouping related values together. This article breaks down how to define, use, and manipulate structs using practical examples.


🔹 1. What Is a Struct?

A struct (short for “structure”) is a custom data type in Go that groups related variables (called fields) together under one name.

Think of it as a container for data that belongs together.

🧪 Defining a Struct

type Person struct {
    name string
    age  int
}

🔹 2. Creating Struct Instances

✅ Method 1: Named Fields

p1 := Person{name: "Amit", age: 30}
p2 := Person{"Rahul", 28}

✅ Method 3: Declare then Assign

var p3 Person
p3.name = "Neha"
p3.age = 25

🔹 3. Accessing and Updating Fields

fmt.Println(p1.name) // Output: Amit
p1.age = 31
fmt.Println(p1.age) // Output: 31

🔹 4. Passing Structs to Functions

Structs can be passed by value or by pointer.

📦 By Value (Copy):

func printPerson(p Person) {
    fmt.Println(p.name, p.age)
}

🪝 By Pointer (Modify Original):

func birthday(p *Person) {
    p.age++
}

🔹 5. Nested Structs

You can define structs inside other structs.

type Address struct {
    city  string
    state string
}

type Employee struct {
    name    string
    age     int
    address Address
}

🧪 Example:

emp := Employee{
    name: "Sita",
    age:  29,
    address: Address{
        city:  "Bangalore",
        state: "Karnataka",
    },
}
fmt.Println(emp.name, "from", emp.address.city)

🔹 6. Anonymous Structs (Quick Use)

temp := struct {
    brand string
    year  int
}{
    brand: "Toyota",
    year:  2020,
}

🔹 7. Structs vs Maps (When to Use What)

FeatureStructMap
Fixed fields✅ Yes❌ No
Field typesMixed types allowedValues must be same type
ReadabilityHigh (explicit)Medium (key strings)
Use caseKnown structure (User, Book)Dynamic/unknown fields (JSON)

🧪 Try It Yourself

  1. Create a Book struct with title, author, and price

  2. Write a function that prints the book details

  3. Add a nested Publisher struct inside the Book struct


✅ Summary

  • Structs group related data into one clean type

  • You can access, update, and pass them to functions

  • Nested structs allow you to model real-world hierarchies

  • Use structs when the shape of your data is known and fixed


📘 Next: “Methods in Go – Attaching Behavior to Structs”
📢 Follow for more beginner-friendly Go tutorials!

0
Subscribe to my newsletter

Read articles from Prajwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prajwal
Prajwal

Computer Science Enthusiast