Hi Gophers,
I was given a task where, given two maps, each of different length and common + different key value pairs, I have to create another map, that would contain the common elements between the two maps + the unique elements of the two maps. Care should be taken that:
- Neither of the maps should be modified. The key value pairs must be inserted in a different , new map.
- The function should return the first, second and the new map.
Here’s how I have written the code:
package main
import "fmt"
func main() {
fmt.Println("vim-go")
numToWords := map[string]int{
"oneHundred": 100,
"twoHundred": 200,
"threeHundred": 300,
"fourHundred": 400,
"sixHundred": 600,
}
sameNumToWords := map[string]int{
"oneHundred": 100,
"twoHundred": 200,
"threeHundred": 300,
"fiveHundred": 500,
}
map1, map2, mixMap := mixOfTwo(numToWords, sameNumToWords)
fmt.Printf("first Map: %v\n", map1)
fmt.Printf("second Map: %v\n", map2)
fmt.Printf("mixOfTwo Map: %v\n", mixMap)
}
func mixOfTwo(first map[string]int, second map[string]int) (map[string]int,
map[string]int, map[string]int) {
mixOfTwoMaps := make(map[string]int)
for firstKey, _ := range first {
if _, ok := mixOfTwoMaps[firstKey]; ok == false {
mixOfTwoMaps[firstKey] = first[firstKey]
}
}
for secondKey, _ := range second {
if _, ok := mixOfTwoMaps[secondKey]; ok == false {
mixOfTwoMaps[secondKey] = second[secondKey]
}
}
return first, second, mixOfTwoMaps
}
Here’s the output:
>go run main.go
vim-go
first Map: map[fourHundred:400 oneHundred:100 sixHundred:600 threeHundred:300 twoHundred:200]
second Map: map[fiveHundred:500 oneHundred:100 threeHundred:300 twoHundred:200]
mixOfTwo Map: map[fiveHundred:500 fourHundred:400 oneHundred:100 sixHundred:600 threeHundred:300 twoHundred:200]
While this works fine, I would like to know if Golang has a way in which I can loop over more than one map. For example:
for key1, value1 ;key2, value2 := range map1;map2?
Also, as usual, if there is a better, more efficient way of writing the code, kindly let me know.