0

Suppose I have a map like:

m := map[string]interface{}{}

Now I get a string "a", I want to know if there's value in m["a"], how can I tell?

As I can see now, m["a"] is never nil, so I can't compare it to nil to see if there's anything. Also, there's not a keyword named undefined to do that..

jiyinyiyong
  • 4,586
  • 7
  • 45
  • 88

1 Answers1

4

map access returns two values, the second one being a boolean telling you if there's a value.

You can use this standard idiom :

if elm, ok := m["a"]; ok {
    // there's an element
} else {
    // no element
} 

Documentation

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758