To merge two maps in Go, you can use a for loop to iterate over one map and add its key-value pairs to the other map. This method provides a straightforward way to combine the contents of two maps.
We can merge two maps in Go by iterating over the second map and adding each key-value pair to the first map using a for loop.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values.map2
and add each key-value pair to map1
.fmt.Println
function to verify the merge.package main
import "fmt"
func main() {
// Declare and initialize two maps
map1 := map[string]int{"one": 1, "two": 2}
map2 := map[string]int{"three": 3, "four": 4}
// Merge map2 into map1
for key, value := range map2 {
map1[key] = value
}
// Print the merged map
fmt.Println("Merged Map:", map1)
}
Merged Map: map[one:1 two:2 three:3 four:4]
We can merge two maps in Go and handle overlapping keys by iterating over the second map and adding each key-value pair to the first map using a for loop. If a key exists in both maps, the value from the second map will overwrite the value in the first map.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values, and there is an overlapping key.map2
and add each key-value pair to map1
, updating the value if the key already exists.fmt.Println
function to verify the merge.package main
import "fmt"
func main() {
// Declare and initialize two maps with overlapping keys
map1 := map[string]int{"one": 1, "two": 2}
map2 := map[string]int{"two": 22, "three": 3}
// Merge map2 into map1, updating values for overlapping keys
for key, value := range map2 {
map1[key] = value
}
// Print the merged map
fmt.Println("Merged Map:", map1)
}
Merged Map: map[one:1 two:22 three:3]
We can create a helper function to merge two maps in Go, which provides a reusable way to combine the contents of two maps.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values.mergeMaps
that takes two maps as parameters and returns a merged map.map1
and map2
as arguments and store the result in a variable named mergedMap
.fmt.Println
function to verify the merge.package main
import "fmt"
func mergeMaps(map1, map2 map[string]int) map[string]int {
for key, value := range map2 {
map1[key] = value
}
return map1
}
func main() {
// Declare and initialize two maps
map1 := map[string]int{"one": 1, "two": 2}
map2 := map[string]int{"three": 3, "four": 4}
// Merge the maps using the helper function
mergedMap := mergeMaps(map1, map2)
// Print the merged map
fmt.Println("Merged Map:", mergedMap)
}
Merged Map: map[one:1 two:2 three:3 four:4]
In this tutorial, we learned How to Merge Two Maps in Go language with well detailed examples.