How to Copy a Map in Go

1. Introduction

Copying a map in Go is an operation that is sometimes necessary when you need to duplicate map content while ensuring that changes to the new map do not affect the original. In this blog post, we will go over how to perform a deep copy of a map in Go, which is not directly supported by the language's built-in functionality.

2. Program Steps

1. Create and populate an original map.

2. Declare a new map of the same type.

3. Iterate over the original map and copy each key-value pair to the new map.

4. Print both maps to demonstrate that they contain the same data but are separate objects.

3. Code Program

Copying a map in Go involves creating a new map and then iterating over the original map to copy each key-value pair. This process is known as a deep copy because it duplicates the actual data the map holds, rather than just copying references.

Here is the complete Go program to demonstrate how to copy a Map:
package main

import "fmt"

// copyMap creates a deep copy of the provided map
func copyMap(originalMap map[string]int) map[string]int {
	newMap := make(map[string]int)
	for key, value := range originalMap {
		newMap[key] = value
	}
	return newMap
}

func main() {
	// Step 1: Create and populate an original map
	originalMap := map[string]int{"one": 1, "two": 2, "three": 3}
	fmt.Println("Original map:", originalMap)

	// Steps 2 and 3: Declare a new map and copy the original map
	copiedMap := copyMap(originalMap)

	// Step 4: Print the new map
	fmt.Println("Copied map:", copiedMap)
}

Output:

Original map: map[one:1 three:3 two:2]
Copied map: map[one:1 three:3 two:2]

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for input and output.

3. copyMap function - Takes a map as an argument and returns a new map that is a deep copy of the original.

4. originalMap - A map with string keys and integer values is declared and initialized.

5. The copyMap function is called with originalMap as the argument, creating copiedMap as its deep copy.

6. Both originalMap and copiedMap are printed, showing that they contain the same data.

7. The output demonstrates that copiedMap is an exact replica of originalMap, confirming the deep copy operation.


Comments