Welcome to our tutorial on Go (Golang)! In this lesson, we'll learn how to check for the existence of keys in maps. By the end of this tutorial, you'll be able to confidently use key checking techniques in your Go projects. šÆ
A map in Go is a collection of key-value pairs. It's similar to an object in other programming languages. Each key is unique and corresponds to one value.
// Creating a map
myMap := make(map[string]string)To check if a key exists in a map, Go does not provide a built-in function like other languages (e.g., JavaScript's myMap.hasOwnProperty('key')). However, we can create a simple function to achieve this.
ContainsKey Function šfunc ContainsKey(myMap map[string]string, key string) bool {
_, exists := myMap[key]
return exists
}š” Pro Tip: The _, exists := myMap[key] line returns two values: the value associated with the key if it exists, or the zero value of the value type. The variable exists will be true if the key is found in the map.
Let's see an example:
myMap := make(map[string]string)
myMap["name"] = "John"
// Check if the key 'name' exists in the map
exists := ContainsKey(myMap, "name")
if exists {
fmt.Println("Key 'name' exists!")
} else {
fmt.Println("Key 'name' does not exist.")
}Output:
Key 'name' exists!
:::quiz Question: What will be the output of the following code snippet?
myMap := make(map[string]string)
myMap["name"] = "John"
// Check if the key 'non_existent_key' exists in the map
exists := ContainsKey(myMap, "non_existent_key")
if exists {
fmt.Println("Key 'non_existent_key' exists!")
} else {
fmt.Println("Key 'non_existent_key' does not exist.")
}A: Key 'non_existent_key' exists!
B: Key 'non_existent_key' does not exist.
C: Compilation error.
Correct: B
Explanation: The non_existent_key does not exist in the map, so the ContainsKey function will return false, and the output will be "Key 'non_existent_key' does not exist.".