dictionary - How to check if a map contains a key in go? -
i know can iterate on map m by,
for k, v := range m { ... } and key there more efficient way of testing key's existence in map? thanks. couldn't find answer in language spec.
one line answer:
if val, ok := dict["foo"]; ok { //do here } explanation:
if statements in go can include both condition , initialization statement. example above uses both:
initializes 2 variables -
valreceive either value of "foo" map or "zero value" (in case empty string) ,okreceive bool settrueif "foo" present in mapevaluates
ok,trueif "foo" in map
if "foo" indeed present in map, body of if statement executed , val local scope.
Comments
Post a Comment