Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if key exists in multiple maps in one condition

Tags:

dictionary

go

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 it possible to join these two conditions into one? I managed to do something like this:

v1, ok1 := map1["aaa"]
v2, ok2 := map2["aaa"]
if ok1 && ok2 {
 ...
}

but I'm curious whether it (assigning and checking) can be done in one if condition.

like image 554
wrwr Avatar asked Feb 01 '17 11:02

wrwr


People also ask

Is key in map C++?

Use the std::map::contains Function to Check if Key Exists in a C++ Map. contains is another built-in function that can be used to find if the key exists in a map . This function returns a boolean value if the element with the given key exists in the object.

What does map return if key not found C++?

map find() function in C++ STL Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end().

Is Golang map ordered?

As a Golang map is an unordered collection, it does not preserve the order of keys. We can use additional data structures to iterate over these maps in sorted order.


1 Answers

No, it can't be done. Spec: Index expressions:

An index expression on a map a of type map[K]V used in an assignment or initialization of the special form

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]

yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.

So you can use the special v, ok := m[k] form only if nothing else gets assigned.

However, if you don't use the zero value of the value type of the map, you can do the check using a simple tuple-assignment; by not using the special form but 2 simple index expressions.

For example if your value type is some interface type (e.g. interface{}), and you know you don't use the nil value, you may do the following:

if v1, v2 := m1["aaa"], m2["aaa"]; v1 != nil && v2 != nil {
    fmt.Printf("Both map contains key '%s': %v, %v\n", "aaa", v1, v2)
}

Of course with a helper function, you can do it in one step:

func idx(m1, m2 map[string]interface{}, k string) (
    v1, v2 interface{}, ok1, ok2 bool) {

    v1, ok1 = m1[k]
    v2, ok2 = m2[k]
    return
}

Using it:

if v1, v2, ok1, ok2 := idx(m1, m2, "aaa"); ok1 && ok2 {
    fmt.Printf("Both map contains key '%s': %v, %v\n", "aaa", v1, v2)
}

Try the examples on the Go Playground.

like image 159
icza Avatar answered Nov 16 '22 00:11

icza