Golang : Check if element exist in map
Key based element search on a map is the most frequent method use to retrieve the associated value. However, there are times when a search will fail and cause panic if the element is not in the map at the first place. The codes below will show you how to check if an element exist in a map or not.
package main
import "fmt"
func main() {
cities := map[string]string{"city1": "New York", "city2": "Portland"}
// ok is boolean
value, ok := cities["city2"] // return value if found or ok=false if not found
if ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
// try something else
if value, ok = cities["city3"]; ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
}
Output :
value: Portland
key not found
Reference :
See also : Golang : How to delete element(data) from map ?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+40.4k Golang : UDP client server read write example
+17.2k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+11.6k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+20.9k Golang : Secure(TLS) connection between server and client
+11.8k Golang : Fuzzy string search or approximate string matching example
+9.4k Golang : How to check if a string with spaces in between is numeric?
+9.2k Golang : Gonum standard normal random numbers example
+37.8k Upload multiple files with Go
+11.9k How to tell if a binary(executable) file or web application is built with Golang?
+31.1k Golang : Interpolating or substituting variables in string examples
+10.5k Golang : Detect number of faces or vehicles in a photo
+15k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name