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
+8.6k Golang : Populate slice with sequential integers example
+6k Golang : Fibonacci number generator examples
+11.6k Golang : Pass database connection to function called from another package and HTTP Handler
+10.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+7.9k Golang : automatically figure out array length(size) with three dots
+20.6k Golang : Match strings by wildcard patterns with filepath.Match() function
+30.6k Golang : Validate email address with regular expression
+7.8k Yum Error: no such table: packages
+3.7k Chrome : How to block socketloop.com links in Google SERP?
+7.4k Golang : On lambda, anonymous, inline functions and function literals
+8k Golang : How to extract video or image files from html source code
+3.8k Python : Find out the variable type and determine the type with simple test