I need to check if the same key exists in two maps:
if v1, ok1 := map1[\"aaa\"]; ok1 {
...
}
if v2, ok2 := map2[\"aaa\"]; ok2 {
...
}
Is
you could also use variadic parameter(three dots) to check multiple keys :
// check map 1 and map2 is null or not
func checkMap(m1, m2 map[string]interface{}, keys ...string) []bool {
var isExist []bool
for key := range keys {
//checking value from map 1
_, ok := m1[keys[key]]
if ok {
isExist = append(isExist, true) // append for the first time to avoid panic
} else {
isExist = append(isExist, false) // append for the first time to avoid panic
}
// checking value from map2
_, ok = m2[keys[key]]
if ok {
isExist[key] = true
} else {
isExist[key] = false
}
}
return isExist
}
And then you can check your keys in order like this :
result := checkMap(myMap, myMap2, "a", "b", "c", "d", "e", "f", "g")
fmt.Printf("result = %+v\n", result) // print the result
if result[0] {
fmt.Println("key a exist in both map")
}
if result[1] {
fmt.Println("key b exist in both map")
}