How to create and use maps (hash tables) in Go?

In Go, maps can be created and used to store key-value pairs. Here is how you can create and use maps:

  1. 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, }
  2. Adding/Updating values in a Map:

    myMap[key] = value // Add/Update value for the given key
  3. Accessing values from a Map:

    value := myMap[key] // Retrieve value for the given key
  4. Deleting values from a Map:

    delete(myMap, key) // Delete value for the given key
  5. 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 }
  6. Iterating over a Map:

    for key, value := range myMap { // Access the key and value pairs }
  7. 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.