Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if struct exists for key in map

Tags:

dictionary

go

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==?) {
 ...
}
like image 424
Allen Avatar asked Dec 03 '25 17:12

Allen


1 Answers

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 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 in your code:

type Hello struct{}
structMap := map[string]Hello{}
if j, ok := structMap["example"]; !ok {
    // "example" is not in the map
}
like image 81
icza Avatar answered Dec 06 '25 11:12

icza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!