How to check if a value exists in a map in Golang
In this shot, we will learn to check if a value exists in a map using Golang.
No built-in function checks if a value exists in a map in Golang.
So, we will use the following approach to check if a value exists in a map:
- Traverse through the entire map.
- Check if the present value is equal to the value the user wants to check.
-
If it is equal and is found, print the value.
-
Otherwise, print that the value is not found in the map.
-
Example
In this example, we will have a dictionary where the student names are the key, and their ages are the value.
We will check whether or not students of a certain age are present.
Code
package main//program execution starts herefunc main(){//declare a mapstudents := map[string]int{"john": 10,"james": 12,"mary":13,}//provide user valuevar userValue = 10//call function and proceed according to returnif checkForValue(userValue,students){//executes if a value is present in the mapprintln("Value found")}else{//executes if a value is NOT present in the mapprintln("Value NOT found in the map")}}//function to check if a value present in the mapfunc checkForValue(userValue int, students map[string]int)bool{//traverse through the mapfor _,value:= range students{//check if present value is equals to userValueif(value == userValue){//if same return truereturn true}}//if value not found return falsereturn false}
Explanation
-
We declare and initialize a map
students, with the key as the student’s name and the value as their age. -
Line 14: We provide user input.
-
Line 30: We declare the function that accepts the
userValueandstudentsas parameters and returns a boolean value.-
Line 33: We traverse through the map,
students, and check if the present value equals theuserValue. If it is equal, returntrue. -
Line 44: If the
userValueis not found in the map after traversing, returnfalse.
-
-
Line 17: We call the
checkForValuefunction and use anifstatement to check if the returned value istrueorfalse. We then display the output accordingly.