How to merge two maps in Go?

To merge two maps in Go, you can follow these steps:

  1. Create a new result map to store the merged map.
  2. Iterate over the first map using a for range loop.
  3. For each key-value pair in the first map, add the key-value pair to the result map.
  4. Iterate over the second map using a for range loop.
  5. For each key-value pair in the second map, check if the key exists in the result map.
    • If the key exists in the result map, update the value with the value from the second map.
    • If the key does not exist in the result map, add the key-value pair to the result map.
  6. At the end of the loops, the result map will contain the merged map.

Here's an example implementation:

func mergeMaps(m1, m2 map[string]int) map[string]int { result := make(map[string]int) // Merge m1 into result for key, value := range m1 { result[key] = value } // Merge m2 into result, updating values if keys exist for key, value := range m2 { result[key] = value } return result }

This function takes two maps as input m1 and m2 with string keys and int values and returns a new merged map. You can modify the function based on your specific map types and key-value types.