Check for a Key
Lesson 20 of 21 in Coddy's Slices and Maps in Golang course.
Until this point, we've learned how to add and delete values from maps. In this lesson, we'll learn how to check if a map contains a specific key. We can do this using the if condition, as shown in the following example:
var books = map[string]int{
"Golang": 1,
"Python": 2,
"Rust": 3,
}
if v, k := books["Python"]; k{
fmt.Println(v)
}In this example, we have a map called books. Using if, we check if the map contains the key "Python". If it does, we print the associated value. In our example, the result will be 2.
The k in <strong>books["Python"]; k{</strong> holds a boolean value, either true or false. If the key exists, it will return true, and we can check this by printing it to the screen:
if v, k := books["Python"]; k{
fmt.Println(k,v)
}The output will be:
true 1Go has a simplified version of this, which can be done like this:
v, k := books ["a"]
fmt.Println(v, k)This will return the value v and k a boolean value true (if the key exists) or false (if the key does not exist):
0 false
In our case, a is not in the map, so it returns 0 and false.
Challenge
EasyWrite a program that takes an input from the user as a key and checks if this key exists in the given map:
- If it exists, print the message
<strong>"{key} exists with a value of {value}"</strong>.
{key} is the key entered by the user, and {value} is the corresponding value in the map. - If it does not exist, print
<strong>"{key} does not exist in the map"</strong>.
Try it yourself
package main
import "fmt"
func main() {
// Take input from the user as a key Don't Change this!
var key string
fmt.Scanln(&key)
// Books map Don't Change this!
books := map[string]int{
"Golang": 1,
"Python": 2,
"Rust": 3,
"Lua": 4,
"Java": 5,
}
// Check if the key exists in the map
}All lessons in Slices and Maps in Golang
1Introduction
Introduction