Whatever the name may be, maps are incredibly versatile and provide an easy and fast way to retrieve, update, or delete data using the keys.
In this friendly tutorial, you will learn how to check if a key exists in a map using the go programming language.
The Basics
Before we check if a map is in a key, let us start with how to create a map in GO.
To create a map in Go, use the example syntax shown below:
map[key_data_type]value_data_type{key_1: value_1, ..., key_N: value_N} // map with data
The example below creates a map of strings:
1: "Ubuntu",
2: "Debian"
3: "Fedora"
4: "OpenSUSE"
5: "Manjaro",
}
Retrieve Values in Map
We will need to retrieve a value associated with a specific key in a map in most cases. Go provides us with a very simple method to accomplish this task.
The syntax is as shown:
We can access a value stored in a specific key by calling the map name and passing the target key inside a pair of square brackets.
An example is as shown:
The above should retrieve the value in key number 4. The resulting output is as shown:
OpenSUSE
Although this is a simple technique to retrieve a value based on a key, it can sometimes confuse if a key is not in a map.
What happens when you try to retrieve a value for a non-existent key?
..> 0
The above code returns 0 since there is no key “0” here.
But what if you had a key holding the actual value “0”? How do you tell if the key is not there or the value is 0?
Check if Key Exists in Map
Therefore, it is prudent to have a way to tell if a key is there or the value is just 0. We can use the syntax as shown:
The found parameter holds a Boolean value. If the key is in the map, the found parameter is true and false.
Hmm, cool!
We can use this functionality to implement a conditional statement based on the value of the found variable.
An example is as shown:
states := map[string]string{
"CO": "Colorado",
"DE": "Delaware",
"LA": "Louisiana",
"MA": "Massachusetts",
"VT": "Vermont",
}
if _, found := states["MA"]; found {
fmt.Printf("Found")
} else {
fmt.Println("Not Found")
}
}
In the example above, we use an if statement to check if a key is in the map using the found parameter.
The resulting code is as shown:
Not Found
This method will work efficiently even if the value of the specified key is equal to 0 or true/false.
Conclusion
In this article, you learned how to access values in a map using the associated key and check if a key is in a map.
Thanks for reading and Happy code mode!