Can I have a function to check if a key is in a map?

Viewed 2074

I want to have a function like Map.containsKey() in Go, since Go itself does not provide this kind of functionality, can I alternatively have a custom function like MapContainsKey(someMap map[K]V, key K) in Go?

I do not know how to realize it because as far as I know there is no generics in Go yet.

I know I can do

if val, ok := someMap[key]; ok{
   // some code here
}

but I want to wrap it in a function.

2 Answers

You could create a function which uses reflection and be "generic", but it would be slower. In Go you just write what you already have. Clean, fast, readable. Go is not Java.

For demonstration, here's how it would look like. Type checks are omitted (it would panic if you pass a non-map for example, or you pass a key value whose type doesn't match the map's key type):

func containsKey(m, k interface{}) bool {
    v := reflect.ValueOf(m).MapIndex(reflect.ValueOf(k))
    return v != reflect.Value{}
}

Example testing it:

m1 := map[string]int{"one": 1, "x": 0}
fmt.Println(containsKey(m1, "one"))
fmt.Println(containsKey(m1, "x"))
fmt.Println(containsKey(m1, "two"))

m2 := map[int]string{1: "one", 9: ""}
fmt.Println(containsKey(m2, 1))
fmt.Println(containsKey(m2, 9))
fmt.Println(containsKey(m2, 2))

Output (try it on the Go Playground):

true
true
false
true
true
false

As you said there is this solution :

if _, ok := aMap[key]; ok {
  // bla bla bla
}

If you want to wrap it in a function, then make this function :

type (
    myMap1 map[int]string
    myMap2 map[string]string
)

func (m myMap1) Contains(k int) (ok bool) {
    _, ok = m[k]
    return
}

func (m myMap2) Contains(k string) (ok bool) {
    _, ok = m[k]
    return
}

func main() {
    m1 := make(myMap1)
    m2 := make(myMap2)

    m1[10] = "Hello"

    m2["Hi"] = "こんにちは"

    fmt.Println(m1.Contains(9))  // false
    fmt.Println(m1.Contains(10)) // true

    fmt.Println(m2.Contains("Hello")) // false
    fmt.Println(m2.Contains("Hi"))    // true
}

I hope this answers your question

Related