Sling Academy
Home/Golang/How to Merge Two Maps in Go

How to Merge Two Maps in Go

Last updated: November 24, 2024

Understanding Maps in Go

Maps in Go are similar to dictionaries or hashtables in other programming languages. They store data in key-value pairs where each key is unique. The typical operations performed on maps include addition, retrieval, and deletion of key-value pairs.

Merging Two Maps

Merging two maps involves combining their key-value pairs. If both maps contain the same key, you'll need to decide which map's value to keep, or how to handle that conflict. Let's start with basic examples and then gradually move to more complex scenarios.

Basic Example

package main

import "fmt"

func main() {
    map1 := map[string]int{"apple": 3, "banana": 2}
    map2 := map[string]int{"banana": 4, "cherry": 5}
    mergedMap := mergeMaps(map1, map2)
    fmt.Println(mergedMap) // Output: map[apple:3 banana:4 cherry:5]
}

func mergeMaps(map1, map2 map[string]int) map[string]int {
    merged := make(map[string]int)
    for k, v := range map1 {
        merged[k] = v
    }
    for k, v := range map2 {
        merged[k] = v
    }
    return merged
}

In the above example, when both maps have a common key "banana", the value from map2 is used in the merged result.

Intermediate Example: Customize Conflict Resolution

package main

import "fmt"

func main() {
    map1 := map[string]int{"apple": 3, "banana": 2}
    map2 := map[string]int{"banana": 4, "cherry": 5}
    mergedMap := mergeMapsWithPreference(map1, map2, true)
    fmt.Println(mergedMap) //Output when preferFirst is true: map[apple:3 banana:2 cherry:5]
}

func mergeMapsWithPreference(map1, map2 map[string]int, preferFirst bool) map[string]int {
    merged := make(map[string]int)
    for k, v := range map1 {
        merged[k] = v
    }
    for k, v := range map2 {
        if _, found := merged[k]; found {
            if !preferFirst {
                merged[k] = v
            }
        } else {
            merged[k] = v
        }
    }
    return merged
}

This version of the merge function allows you to choose which map's values to prioritize in case of key conflicts using a preferFirst flag.

Advanced Example: Handling Complex Value Types

If your maps contain complex data types as values, you might want to merge them differently. Here's an example with maps storing slices:

package main

import "fmt"

func main() {
    map1 := map[string][]int{"fruits": {1, 2}}
    map2 := map[string][]int{"fruits": {3, 4}, "veggies": {5, 6}}
    mergedMap := mergeComplexMaps(map1, map2)
    fmt.Println(mergedMap) // Output: map[fruits:[1 2 3 4] veggies:[5 6]]
}

func mergeComplexMaps(map1, map2 map[string][]int) map[string][]int {
    merged := make(map[string][]int)
    for k, v := range map1 {
        merged[k] = append([]int{}, v...)
    }
    for k, v := range map2 {
        if existing, found := merged[k]; found {
            merged[k] = append(existing, v...)
        } else {
            merged[k] = append([]int{}, v...)
        }
    }
    return merged
}

This function appends slices from two maps instead of overriding them, offering a clear indication of how to handle more complicated map value types during a merge.

Conclusion

Merging maps in Go can be performed in various ways depending on the data types and specific requirements for handling key conflicts. Understanding and manipulating with fundamental Go concepts like loops and slices is necessary for conducting these operations efficiently. Adjust these examples to suit your specific use case and data structure.

Next Article: Converting Maps to JSON and Back in Go

Previous Article: Using Maps to Group Data by Categories in Go

Series: Working with Maps in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant