In this shot, we will learn to check if the Golang map contains a key.
We can use if statements in Golang to check if a key is present in the map or not.
if val, ok := map["key"]; ok {
//do
}else{
}
If a map has key, then ok has the bool value true, and val contains a value of that key.
We can have an else statement to handle if the map doesn’t contain the required key.
In the example below, we have a map students, which contains student names as keys and their age as the value.
We will get the age of a student and handle the else case if a student isn’t found.
package main//program execution starts herefunc main(){//declare a mapstudents := map[string]int{"john": 10,"james": 12,"mary":13,}//check if john is present in mapif val, ok := students["john"]; ok {print(val)}else{print("No record found")}}
In the above code:
Line 4: We start program execution from the main() function in Golang.
Line 7: We declare and initialize the map students where the key is of string type, which holds student’s name, and value of int type, which holds student’s age.
Line 14: We check if map students and a key john is present or not.
No record found.When we run the above code snippet, we see the output as 10, which is john's age.
If we try to pass student name robert, which is not in the map students, then the output is No record found. This is because robert is not present in the map students.
package main//program execution starts herefunc main(){//declare a mapstudents := map[string]int{"john": 10,"james": 12,"mary":13,}//check if john is present in mapif val, ok := students["robert"]; ok {print(val)}else{print("No record found")}}