Difference Between Struct and Map in Golang

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

1. Introduction

In Golang, structs and maps are two important data types used to store collections of data. 

A struct is a type that groups together variables of different types under a single name, providing a convenient way to keep related data together. Structs are useful for defining objects with known properties. 

A map, on the other hand, is a collection of key-value pairs, where each unique key maps to a single value. Maps are ideal for storing data with dynamic or unknown structures at compile time.

2. Key Points

1. Type of Collection: Structs are collections of fields, and maps are collections of key-value pairs.

2. Type Safety: Structs are type-safe, maps are not strictly type-safe.

3. Use Case: Structs for fixed data structures, maps for dynamic data structures.

4. Order: Structs have a defined order of fields, maps do not guarantee order.

3. Differences

Characteristic Struct Map
Type of Collection Collection of fields Collection of key-value pairs
Type Safety Type-safe Not strictly type-safe
Use Case Fixed data structures Dynamic data structures
Order Defined order of fields No guaranteed order

4. Example

// Example of a Struct
type Person struct {
    Name string
    Age  int
}

// Example of a Map
personMap := map[string]int{
    "Alice": 30,
    "Bob":   25,
}

Output:

Struct Output:
Person{Name: "Alice", Age: 30}
Map Output:
map[Alice:30 Bob:25]

Explanation:

1. The Person struct creates a fixed structure with a Name and an Age.

2. The personMap is a map that stores ages keyed by names. The structure is more dynamic and can easily add or remove entries.

5. When to use?

- Use structs when you have a fixed set of fields with different types that you want to group together, like defining a model or an object.

- Use maps when you need a more flexible data structure that allows you to add or remove entries easily, and when the keys are not known at compile time.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare