To copy a map in Go, you can use a for loop to iterate over the original map and add its key-value pairs to a new map. This method provides a straightforward way to duplicate a map.
We can copy a map in Go by iterating over the original map and adding each key-value pair to a new map using a for loop.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.copiedMap
.originalMap
and add each key-value pair to copiedMap
.fmt.Println
function to verify the copy.package main
import "fmt"
func main() {
// Declare and initialize a map
originalMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Declare an empty map
copiedMap := make(map[string]int)
// Copy the map using a for loop
for key, value := range originalMap {
copiedMap[key] = value
}
// Print the copied map
fmt.Println("Copied Map:", copiedMap)
}
Copied Map: map[one:1 two:2 three:3]
We can create a helper function to copy a map in Go, which provides a reusable way to duplicate maps.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.copyMap
that takes a map as a parameter and returns a copy of the map.originalMap
as an argument and store the result in a variable named copiedMap
.fmt.Println
function to verify the copy.package main
import "fmt"
func copyMap(original map[string]int) map[string]int {
copied := make(map[string]int)
for key, value := range original {
copied[key] = value
}
return copied
}
func main() {
// Declare and initialize a map
originalMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Copy the map using the helper function
copiedMap := copyMap(originalMap)
// Print the copied map
fmt.Println("Copied Map:", copiedMap)
}
Copied Map: map[one:1 two:2 three:3]
We can copy a map in Go and modify its values during the copying process by iterating over the original map and applying transformations to the values.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.copiedMap
.originalMap
and add each key-value pair to copiedMap
, modifying the values during the copying process (e.g., multiplying each value by 2).fmt.Println
function to verify the copy.package main
import "fmt"
func main() {
// Declare and initialize a map
originalMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Declare an empty map
copiedMap := make(map[string]int)
// Copy the map and modify values
for key, value := range originalMap {
copiedMap[key] = value * 2
}
// Print the copied map
fmt.Println("Copied Map:", copiedMap)
}
Copied Map: map[one:2 two:4 three:6]
In this tutorial, we learned How to Copy a Map in Go language with well detailed examples.