Google News
logo
Golang - Interview Questions
How can we check if the Go map contains a key?
Once the values are stored in key-value pairs in the map, we can retrieve the object by using the key as map_name[key_name] and we can check if the key, say “foo”, is present or not and then perform some operations by using the below code:
if val, ok := dict["foo"]; ok {
    //do something here
}
Explanation :
if statements in Go can include both a condition and an initialization statement. 
 
* initializes two variables - val will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and ok will receive a bool that will be set to true if "foo" was actually present in the map
 
* evaluates ok, which will be true if "foo" was in the map
 
If "foo" is indeed present in the map, the body of the if statement will be executed and val will be local to that scope.
Advertisement