Structs in Go – Modeling Real-World Data

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}
✅ Method 2: Positional Fields (not recommended for readability)
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)
Feature | Struct | Map |
Fixed fields | ✅ Yes | ❌ No |
Field types | Mixed types allowed | Values must be same type |
Readability | High (explicit) | Medium (key strings) |
Use case | Known structure (User, Book) | Dynamic/unknown fields (JSON) |
🧪 Try It Yourself
Create a
Book
struct withtitle
,author
, andprice
Write a function that prints the book details
Add a nested
Publisher
struct inside theBook
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!
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