| 1. |
How can we check if the Go map contains a key? |
|
Answer» A MAP, in general, is a collection of elements grouped in KEY-value pairs. One key refers to one value. Maps provide FASTER access in terms of O(1) COMPLEXITY to the values if the key is known. A map is visualized as shown in the image below: 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, isExists := map_obj["foo"]; isExists { //do steps needed here}From the above code, we can see that two variables are being initialized. The val variable would get the value corresponding to the key “foo” from the map. If no value is present, we get “zero value” and the other variable isExists will get a bool value that will be SET to true if the key “foo” is present in the map else false. Then the isExists condition is evaluated, if the value is true, then the body of the if would be executed. |
|