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
:
If it is equal and is found, print the value.
Otherwise, print that the value is not found in the map.
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.
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}
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 userValue
and students
as parameters and returns a boolean value.
Line 33: We traverse through the map, students
, and check if the present value equals the userValue
. If it is equal, return true
.
Line 44: If the userValue
is not found in the map after traversing, return false
.
Line 17: We call the checkForValue
function and use an if
statement to check if the returned value is true
or false
. We then display the output accordingly.