In Go, maps can be created and used to store key-value pairs. Here is how you can create and use maps:
Initializing a Map:
// Declare and initialize a map
var myMap map[keyType]valueType
// Initialize an empty map
myMap = make(map[keyType]valueType)
// Declare and initialize a map in one line
myMap := make(map[keyType]valueType)
// Initialize a map with values
myMap := map[keyType]valueType{
key1: value1,
key2: value2,
}
Adding/Updating values in a Map:
myMap[key] = value // Add/Update value for the given key
Accessing values from a Map:
value := myMap[key] // Retrieve value for the given key
Deleting values from a Map:
delete(myMap, key) // Delete value for the given key
Checking if a key exists in the Map:
value, ok := myMap[key] // Retrieve value and check if the key exists
if ok {
// Key exists
} else {
// Key does not exist
}
Iterating over a Map:
for key, value := range myMap {
// Access the key and value pairs
}
Length of a Map:
length := len(myMap) // Return the number of key-value pairs in the map
Remember that maps in Go are unordered. If you need a specific order, you should sort and manage the keys externally. Also, be cautious while operating on concurrent maps as they require proper synchronization to avoid concurrent access issues.