In this example, we show how to check if the value exists in Map or not in GoLang with an example.
We check if a value exists by referring to its key.
Go - Map check if a value exists
In the example, we check if a country exists by its code in a Map:
package main
import "fmt"
func main() {
countries := map[string]string{
"IN": "India",
"NP": "Nepal",
"TR": "Turkey",
"JP": "Japan",
"ZW": "Zimbabwe",
}
country := countries["IN"]
fmt.Println(country)
country = countries["JP"]
fmt.Println(country)
country, found := countries["ZW"]
fmt.Println(country, found)
country, found = countries["TR"]
fmt.Println(country, found)
if country, found := countries["NP"]; found {
fmt.Println(country)
}
}
Output:
India Japan Zimbabwe true Turkey true Nepal