0
0
Goprogramming~3 mins

Why structs are used in Go - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if you could keep all your friend's info in one neat package instead of scattered lists?

The Scenario

Imagine you want to keep track of many details about your friends, like their name, age, and phone number, but you try to store each detail separately in different lists or variables.

The Problem

This manual way is confusing and slow because you have to remember which list holds what, and it's easy to mix up data or lose track of which details belong to which friend.

The Solution

Structs let you group all related information about one friend into a single package, making it easy to organize, access, and manage complex data clearly and safely.

Before vs After
Before
var names []string
var ages []int
// Need to keep indexes aligned manually
After
type Friend struct {
  Name string
  Age  int
}
var friends []Friend
What It Enables

Structs enable you to model real-world objects in code, keeping all their details together for easy use and understanding.

Real Life Example

Think of a contact app where each contact has a name, phone, and email; structs let you store each contact's info neatly in one place.

Key Takeaways

Structs group related data into one unit.

They prevent confusion by keeping data organized.

They make your code clearer and easier to manage.