In Go, a map is a built-in data type that provides an unordered collection of key-value pairs. It is somewhat similar to dictionaries in Python or hash maps in other languages. Maps are used to store and retrieve values based on a unique key.
You can declare a map using the map
keyword, specifying the key and value types.
// Declaration
var myMap map[keyType]valueType
// Initialization
myMap = make(map[keyType]valueType)
Or, you can do it in a single line:
myMap := make(map[keyType]valueType)
Adding and Updating Values
myMap[key1] = value1
myMap[key2] = value2
Deleting a Key-Value Pair
delete(myMap, keyToDelete)
Checking if a Key Exists
value, exists := myMap[key]
Iterating Over a Map
for key, value := range myMap {
// Do something with key and value
}
Compare two maps
import "reflect"
reflect.DeepEqual(ma1, map2)
If you look at the source code for reflect.DeepEqual
's Map
case, you'll see that it first checks if both maps are nil, then it checks if they have the same length before finally checking to see if they have the same set of (key, value) pairs.