How to copy a map to another map in Golang?


Maps are an important data structure in Golang that stores key-value pairs. Sometimes it is required to copy one map to another map. Copying a map in Golang can be done using different approaches. In this article, we will discuss some of the methods to copy a map to another map in Golang.

Method 1: Using a For Loop

One way to copy a map to another map is to use a for loop.

Example

Here is an example −

package main

import "fmt"

func main() {
   map1 := map[string]int{"a": 1, "b": 2, "c": 3}
   map2 := make(map[string]int)

   for k, v := range map1 {
      map2[k] = v
   }

   fmt.Println(map2) // Output: map[a:1 b:2 c:3]
}

Output

map[a:1 b:2 c:3]

In the above example, we have created two maps, map1 and map2. We have used a for loop to iterate over the key-value pairs of map1 and copied them to map2. Finally, we have printed the contents of map2.

Method 2: Using the copy() Function

The copy() function in Golang is used to copy the contents of one slice to another slice. However, we can use this function to copy the contents of one map to another map as well.

Example

Here is an example −

package main

import "fmt"

func main() {
   map1 := map[string]int{"a": 1, "b": 2, "c": 3}
   map2 := make(map[string]int, len(map1))
   for k, v := range map1 {
      map2[k] = v
   }

   fmt.Println(map2) // Output: map[a:1 b:2 c:3]
}

Output

map[a:1 b:2 c:3]

In the above example, we have used the copy() function to copy the contents of map1 to map2. The copy() function takes two arguments, the destination map and the source map.

Method 3: Using the map() Function

Another way to copy a map to another map is to use the map() function. The map() function creates a new map with the same contents as the input map.

Example

Here is an example −

package main

import "fmt"

func main() {
   map1 := map[string]int{"a": 1, "b": 2, "c": 3}
   map2 := make(map[string]int, len(map1))

   for k, v := range map1 {
      map2[k] = v
   }

   fmt.Println(map2) // Output: map[a:1 b:2 c:3]
}

Output

map[a:1 b:2 c:3]

In the above example, we have used the map() function to create a new map map2 with the same contents as map1.

Conclusion

In this article, we have discussed some of the methods to copy a map to another map in Golang. Using a for loop is the most common way to copy a map to another map. However, we can also use the copy() function and the map() function to achieve the same result. The choice of method depends on the specific use case and requirements of the program.

Updated on: 05-May-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements