Go Struct

Go Tutorial

Go Struct – Complete Tutorial

In Go (Golang), a struct is a user-defined data type that allows you to group related data together.
It is similar to classes in OOP, but Go structs do not support inheritance.


1️⃣ What is a Struct in Go?

A struct:

  • Groups multiple variables (fields) of different data types

  • Represents real-world entities

  • Is the foundation of Go data modeling

📌 Think of struct as a blueprint for data, not behavior.


2️⃣ Why Use-Structs?

✔ Organize related data
✔ Create custom data types
✔ Improve code readability
✔ Used in APIs, JSON, databases
✔ Essential for Go backend development


3️⃣ Basic-Struct Definition ⭐

Syntax


Example



4️⃣ Creating & Using a Struct ⭐

Method-1: Declare then assign

var s Student
s.Name = "Amit"
s.Age = 21
s.Marks = 85.5

Method 2: Struct Literal (Most Common)

s := Student{
Name: "Ravi",
Age: 22,
Marks: 78.0,
}

Method 3: Without Field Names

s := Student{"Neha", 20, 90.5}

⚠️ Order must match struct definition.


5️⃣ Access Struct Fields

fmt.Println(s.Name)
fmt.Println(s.Age)

6️⃣ Struct with Functions (Methods) ⭐

Method on Struct


Usage:

fmt.Println(s.Result())

📌 This is how Go achieves OOP-like behavior.


7️⃣ Pointer to Struct ⭐ (Very Important)

Passing struct by value copies data.
Use pointer to modify original struct.


✔ Memory efficient
✔ Interview favorite


8️⃣ Anonymous Struct ⭐


✔ Useful for quick, temporary data


9️⃣ Nested Struct ⭐


 

Access:

p.Address.City

🔟 Struct vs Map ⭐ (Interview)

Feature Struct Map
Type safety ✔ Yes ❌ No
Fixed fields ✔ Yes ❌ No
Performance Faster Slower
JSON usage ✔ Excellent

👉 Use structs for fixed models, maps for dynamic data.


1️⃣1️⃣ Struct with JSON (Real-World Use) ⭐⭐

type User struct {
Name string json:"name"
Email string json:"email"
}

📌 Used in REST APIs


1️⃣2️⃣ Common Mistakes ❌

❌ Forgetting to export fields (capital letters)
❌ Passing struct instead of pointer
❌ Using struct when map is better (or vice versa)
❌ Field order mistake in literals


📌 Interview Questions & MCQs

Q1. What is a struct in Go?

A) Function
B) Package
C) User-defined data type
D) Interface

Answer: C


Q2. How do you access struct fields?

A) s->name
B) s[name]
C) s.name
D) s::name

Answer: C


Q3. Why use pointer to struct?

A) Faster compilation
B) Modify original data
C) Avoid syntax
D) Create copy

Answer: B


Q4. Can structs have methods?

A) Yes
B) No

Answer: A


Q5. Struct fields must be capitalized to?

A) Compile
B) Export outside package
C) Use pointer
D) Save memory

Answer: B


🔥 Real-Life Use Cases

✔ API request/response models
✔ Database records
✔ Configuration objects
✔ Backend services
✔ Microservices


✅ Summary

  • Struct = custom data type in Go

  • Groups related fields

  • Supports methods (OOP-style)

  • Use pointers for performance

  • Widely used in APIs & backend

  • Must-know topic for Go interviews

You may also like...