Different ways to copy map in Golang [With Examples]


Written By - Tuan Nguyen
Advertisement

In the previous chapters, we talked about working with maps in Golang. Today, we will discuss how to copy a map to another variable.

maps: Maps are a convenient and powerful built-in data structure that associates values of one type (the key) with values of another type (the element or value). The key can be of any type for which the equality operator is defined, such as integers, floating point, and complex numbers, strings, pointers, interfaces (as long as the dynamic type supports equality), structs and arrays.

Since maps in Go are reference types, you cannot assign one instance to another in order to deep copy a map's contents. However, we will go write functions that have the same purpose as copying.

 

Iterate the map and deep copy it to the other variable

Copy a map[string]int to another variable

We can copy a map by generating a new, empty map and then adding the necessary key-value pairs to the new map by repeatedly iterating over the old map in a for-range loop. It is the most straightforward and effective solution to this issue in Go. The code below shows how to copy a map[string]int to another variable:

package main

import "fmt"

func main() {
	studentScore := map[string]int{
		"Anna":     59,
		"Bob":      74,
		"Charlice": 96,
	}

	// copy a map
	studentScoreCopy := make(map[string]int)
	for k, v := range studentScore {
		studentScoreCopy[k] = v
	}
	studentScore["Daniel"] = 85

	fmt.Println("The original map:")
	fmt.Println(studentScore)
	fmt.Println("--------")

	fmt.Println("The copied map")
	fmt.Println(studentScoreCopy)
}

Output:

The original map:
map[Anna:59 Bob:74 Charlice:96 Daniel:85]
--------
The copied map
map[Anna:59 Bob:74 Charlice:96]

Note that: The output shows that the copied map is a deep clone, therefore changing the map (add, delete elements) has no impact on the original map.

 

Use generics to write a copying map function

With generics, we can write a function that accepts many data type maps. Here is an example of using generics to write copy map function:

package main

import "fmt"

func main() {
	strIntMap := map[string]int64{
		"Anna": 78,
		"Bob":  82,
	}

	intIntMap := map[int64]int64{
		0: 14,
		1: 23,
	}

	copyMap1 := copyMap(strIntMap)
	copyMap2 := copyMap(intIntMap)

	strIntMap["Test"] = 52
	fmt.Println("The orginal map:")
	fmt.Println(strIntMap)
	fmt.Println(intIntMap)

	fmt.Println("---------------")
	fmt.Println("The copy map:")
	fmt.Println(copyMap1)
	fmt.Println(copyMap2)
}

func copyMap[K , V comparable](m map[K]V) map[K]V{
    result := make(map[K]V)
    for k, v := range m {
        result[k] = v
    }
    return result
}

Output:

Advertisement
The orginal map:
map[Anna:78 Bob:82 Test:52]
map[0:14 1:23]
---------------
The copy map:
map[Anna:78 Bob:82]
map[0:14 1:23]

Note that: The output shows that the copied map is a deep clone, therefore changing the map (add, delete elements) has no impact on the original map.

 

Shallow copy a map in golang

Use caution while assigning one map to another to create a shallow copy. In this instance, changing any element will change the data of both maps. Here is an example of swallow copy a map:

package main

import "fmt"

func main() {
	scoreMap := map[string]int{
		"Anan":   85,
		"Daniel": 95,
		"Min":    76,
	}

	scoreMapShallowCopy := scoreMap
	scoreMapShallowCopy["Thien"] = 51
	scoreMap["Charlice"] = 69

	fmt.Println("The original score map:")
	fmt.Println(scoreMap)

	fmt.Println("The copieds core map:")
	fmt.Println(scoreMapShallowCopy)
}

Output:

The original score map:
map[Anan:85 Charlice:69 Daniel:95 Min:76 Thien:51]
The copieds core map:
map[Anan:85 Charlice:69 Daniel:95 Min:76 Thien:51]

 

Summary

In this article, I have showed you some examples of copying a map to another variable. Maps in Go are reference types, if we use shallow copy, any changes will affect both maps. For a deep copy, we can iterate through the original map and assign it to a new variable.

 

References

https://en.wikipedia.org/wiki/Object_copying
https://en.wiktionary.org/wiki/shallow_copy

 

Categories GO

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment