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.3k Golang : Dealing with struct's private part
+17k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+6k Apt-get to install and uninstall Golang
+22.4k Golang : Round float to precision example
+5.2k Golang : What is StructTag and how to get StructTag's value?
+5.8k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+7.3k Golang : Handling Yes No Quit query input
+3.4k Java : Get FX sentiment from website example
+14.5k Golang : Find commonalities in two slices or arrays example
+4.4k Adding Skype actions such as call and chat into web page examples
+9.9k Golang : How to get quoted string into another string?
+12.7k Golang : Get terminal width and height example