Map in Go
Master Go maps: creation, access, mutation, traversal, comparison, and cloning (shallow, JSON deep, recursive deep).
Introduction to Maps
Maps are Go’s key-value collections. They store key-value pairs and support lookup, add, update, and delete by key.
1. What is a Map?
Key-value data structure.
Creating Maps
Create maps with a composite literal or with make(). An uninitialized map is nil and cannot be written to.
1. Map Literal
Most common and readable.
2. make() for Maps
Create an empty map, then add keys.
Accessing & Updating
Access by key with m[key]. Use the two-value form to check whether the key exists. Update by assigning to m[key].
1. Access by Key
Use m[key]. Check presence with second value.
2. Dynamic Key (Variable)
Keys are expressions; use a variable for runtime keys.
3. Updating Values
Assign to m[key] to change the value.
Adding & Deleting Keys
Add a key by assigning to m[key]. Remove a key with delete(m, key).
1. Adding Keys
Assign to a new key.
2. Deleting Keys
Use delete(m, key).
Traversing Maps
Use for range over the map. Iteration order is not guaranteed. Range over keys only, or keys and values together.
1. Range over Keys
for k := range m.
2. Range over Key-Value Pairs
for k, v := range m.
Comparing Maps
Maps are compared by reference. To compare by contents, use reflect.DeepEqual or a custom loop.
1. Reference Comparison
a == b is invalid in Go; if it were allowed, it would be false even when contents are the same.
2. Value Comparison with reflect.DeepEqual
Deep equality of key-value pairs.
Cloning Maps
Shallow clone: copy key-value pairs into a new map. Deep clone: use JSON marshal/unmarshal or a recursive function that copies nested maps and slices.
1. Shallow Clone
Copy keys and values into a new map.
2. Deep Clone (JSON)
Using JSON marshal/unmarshal.
3. Deep Clone (Recursive Function)
Flexible deep clone: primitives copied by value; maps and slices recursively cloned at every nested level.