Merging Maps in Go: A Step-by-Step Guide

Yusuf AkinleyeYusuf Akinleye
6 min read

Introduction

Go is an open-source programming language. It uses a statically typed system, which requires the declaration of variable types at compile-time and generates more efficient machine code; this eliminates the need to check types at runtime and adopts the use of generics, which also further improves its performance.

In this article, we will be covering the basics declaration of data types, appropriate usage of maps in using generics features for added flexibility, brief use of for statement(for-range), and creating a new map result of merged maps.

Creating the Go main function

First, let's create a new file in our text editor named main.go. In this file, we will declare package main at the top, indicating that it is a standalone program. We will also import any necessary built-in packages.

Next, we will create the main function, which will serve as the central point of interaction for all other parts of the application. It is important to note that the Go compiler will only recognize the main function during the compilation and execution of our code.

Below is a sample code to show a simple application in the main function

package main

import "fmt"

func main() {
   fmt.Println("Merging Two Maps Together in Go")

}

Now that we've covered how to create the main function let's look at how to make use of maps.

Maps in Go

In Go, the built-in data type Map allows for the association of one value to another through a key-value pair, similar to a dictionary in Python. It is written as map[keyType]valueType.

In this application, we will utilize a map variable and add key-value pairs. The following is an example of how to declare the map variable.

package main

import "fmt"

func main() {
   // a message to show the purpose of the code
   fmt.Println("Merging Two Maps Together in Go")

   // Define the first map with keys and values of type any 
   map1 := map[string]any{"A": 2, "B": 4, "C": 6, "D": 8, "E": 10}


   // Define the second map with keys and values of type any
   map2 := map[string]any{"F": 12, "G": 14, "H": 16, "I": 18, "J": 20}

}

We updated our previous code by declaring two variables of the type map, with a key of type string and a value of type any (the generic type that can represent any other type). The type any can be implemented using the interface{} type, which allows for more than one type. In this case, the specific mapped values we are using are even numbers.

Now that we've explained how to declare map variables with their key-value pair types let's look at how to use maps.

Merging Maps

Before we code things out, let's discuss briefly merging maps in Go.

Merging maps means joining two or more maps into a single map with distinct key-value pairs. This involves taking the key of each of the maps in question and combining or mapping their keys to each of their respective value in a newly created map. The use of maps helps a lot in grouping and combining data from different sources into a unified, easy-to-process data structure.

To get this done, we will make use of the for statement, which is the only looping keyword in Go and can be used in different ways.

Here is a brief overview of the use of for statements in Go. Go has several statement variations to suit different needs. The type of for statement depends on the use case.

  • With a Condition: This for statement works similarly to executing multiple if statements and can be used as a basic while loop in dynamically typed languages like Python.

      package main
      import  'fmt'
    
      func main(){
        x := 1
        for x < 30 {
          fmt.Printf("%d Hello", x)
          x = x + 1
        }
      }
    
  • Complete Declaration: This type of for statement is similar to for loops in other programming languages like C, C++, and Java. It consists of variable initialization, a comparison expression evaluating to bool, and an increment/decrement.

      package main
      import  'fmt'
    
      func main(){
        for x := 0; x < 10; x++ {
          fmt.Println(x)
        }
      }
    
  • Infinite Loop: In Go, there is no built-in while function. However, a for loop with no condition or expression serves as an infinite loop in Go.

      package main
      import  'fmt'
    
      func main(){
        for {
          fmt.Println("Hello")
        }
        for i, v := range mySlice {
          fmt.Println(i, v)
        }
      }
    
  • For-Range: This type of for statement is used to iterate over elements in Go's built-in types, such as strings, maps, slices, and arrays. Iterating through the ranged elements, we get two loop variables,: the position(index) and the value at that same position, respectively.

      package main
      import  'fmt'
    
      func main(){
        myElements := []string{"A", "B", "C", "D", "E"}  
        for i, v := range myElements {
          fmt.Println(i, v)
        }
      }
    

In this tutorial, we will be making use of the for-range loop with maps. We can try out this sample code on go-playground here.

func MergeMaps(map1, map2 map[string]any) map[string]any {
   UniqueMap := make(map[string]any)

   // for loop for the first map
   for key, val := range map1 {
       UniqueMap[key] = val
   }

   // for loop for the second map
   for key, val := range map2 {
       UniqueMap[key] = val
   }
   // return merged result
   return UniqueMap
}

We declare the creation of a map variable named UniqueMap using the make function, setting its default size to zero. Then, using a for-range loop, we iterate through each of the map parameters passed to the MergeMaps function.

The element loop consists of the key-value variable of the map. Within the loop, we add the key and value of each map to the UniqueMap variable, causing it to grow as we add key-value pairs automatically.

Finally, we return the modified UniqueMap, which is the result of merging the two maps, and have it printed in the main function by calling the MergeMap function.

Now that we've learned how to merge two maps let's look at the full code below.

The complete source code for the application

package main

import "fmt"

func main() {
   fmt.Println("Merging Two Maps Together in Go")

   //First map 
   map1 := map[string]any{"A": 2, "B": 4, "C": 6, "D": 8, "E": 10}


   // second map
   map2 := map[string]any{"F": 12, "G": 14, "H": 16, "I": 18, "J": 20}
   fmt.Println(MergeMaps(map1, map2))
}

func MergeMaps(map1, map2 map[string]any) map[string]any {
   UniqueMap := make(map[string]any)

   // for loop for the first map
   for key, val := range map1 {
       UniqueMap[key] = val
   }

   // for loop for the second map
   for key, val := range map2 {
       UniqueMap[key] = val
   }
   // return merged result
   return UniqueMap
}

Conclusion

This article showed us the procedure to merge two maps into a single map as well as using generics features to state the types of the key-value pairs used.

Thank you for taking the time to read. Wishing you happy coding ๐Ÿ˜€.

1
Subscribe to my newsletter

Read articles from Yusuf Akinleye directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yusuf Akinleye
Yusuf Akinleye

Software Engineer and Technical writer