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 - val receive either value of "foo" map or "zero value" (in case empty string) , ok receive bool set true if "foo" present in map

  • evaluates ok, true if "foo" in map

if "foo" indeed present in map, body of if statement executed , val local scope.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -