How to check value exists in a map Golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To check value exists in a golang map, use if...else statement with loop of map if any iteration value match with your value it’s means map contains your value.

Today, I’m going show you how do i check value exists in golang map.

Let’s start

Check value exists in golang map

Here, we will create s sample map with some data and try to check value contain in map.

package main

func isValueExists(userValue string, mymap map[string]string)bool{
  for _, value:= range mymap{
    if(value == userValue){
      return true
    }
  }
  return false
}

func main() {
  mymap := make(map[string]string)
  mymap["first"] = "aguidehub"
  mymap["second"] = "infinitbility"
  mymap["third"] = "sortoutcode"
  
  userValue := "aguidehub"

  if isValueExists(userValue,mymap){
    println("Value Exists")
  }else{
    println("Value NOT Exists")
  }
}

In the above program, we are trying to check value in map, let’s see the output.

Output:

Value Exists

Try it yourself

All the best 👍