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
+7.1k Golang : Transform lisp or spinal case to Pascal case example
+15.2k Golang : Get query string value on a POST request
+13.5k Golang : Qt progress dialog example
+9.5k Golang : Read file with ioutil
+7.7k Golang : Scan files for certain pattern and rename part of the files
+32.6k Golang : Regular Expression for alphanumeric and underscore
+9.9k Golang : Convert octal value to string to deal with leading zero problem
+16.4k Golang : Send email and SMTP configuration example
+7.8k Golang Hello World Example
+21.3k Curl usage examples with Golang
+24k Golang : Upload to S3 with official aws-sdk-go package
+16.2k Golang : convert string or integer to big.Int type