According to the Golang documentation on maps,
If the requested key doesn't exist, we get the value type's zero value. In this case the value type is int, so the zero value is 0:
j := m["root"] // j == 0
So I'm trying to determine if a struct exists with a given string, how would I determine this? Would I just check for an empty struct with zerod values? What would the comparison here look like?
type Hello struct{}
structMap := map[string]Hello{}
j := structMap["example"]
if(j==?) {
...
}
Use the special "comma, ok" form which tells if the key was found in the map. Go Spec: Index Expressions:
An index expression on a map
a
of typemap[K]V
used in an assignment or initialization of the special formv, ok = a[x] v, ok := a[x] var v, ok = a[x]
yields an additional untyped boolean value. The value of
ok
istrue
if the keyx
is present in the map, andfalse
otherwise.
So in your code:
type Hello struct{}
structMap := map[string]Hello{}
if j, ok := structMap["example"]; !ok {
// "example" is not in the map
}