In Go, a map is a built-in data type used to store data in key–value pairs.
Each key is unique and maps to a specific value, making maps ideal for fast
lookups and dynamic data storage.
Unlike arrays or slices, maps are:
Unordered (no guaranteed iteration order)
Mutable (you can add, update, and delete elements)
Reference types (they point to an underlying hash table)
Key Features of Maps
Store data as key:value pairs
Keys must be unique (no duplicates allowed)
The len() function returns the number of elements
The zero value of a map is nil
Internally implemented using a hash table for efficient access
Creating Maps in Go
1. Using Map Literals
Note: Map output order may vary because maps are unordered.
2. Using the make() Function
Creating an Empty Map Safely
var m1 = make(map[string]int) // initialized and ready to use var m2
map[string]int // nil map (not initialized)
Writing to m1 works normally
Writing to m2 will cause a runtime panic
Allowed Key and Value Types
Valid Key Types
Keys must support the == operator:
Numbers (int, float, etc.)
Strings
Booleans
Arrays
Structs
Pointers
Interfaces (if comparable)
Invalid Key Types
These cannot be used as keys:
Slices
Maps
Functions
Value Types
Map values can be of any data type.
Accessing, Adding, and Deleting Elements
Accessing Map Elements
Adding, Updating, and Deleting Elements
Checking if a Key Exists
Checking if a key exists avoids confusion when a key might legitimately be
stored with a zero value.
Maps Are Reference Types
Maps do not store data directly—they reference an underlying structure.
Assigning one map to another shares the same data.
Both variables reflect the same change.
Iterating Over a Map
The iteration order is not guaranteed.
Iterating in a Specific Order
To control the order, use a separate slice of keys: