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
+5.4k Golang : Return multiple values from function
+18.7k Golang : Get download file size
+4.5k Java : Generate multiplication table example
+38.1k Golang : Read a text file and replace certain words
+7.3k Golang : alternative to os.Exit() function
+5.8k Get website traffic ranking with Similar Web or Alexa
+6.9k Fix sudo yum hang problem with no output or error messages
+9.3k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+6.2k Linux/Unix : Commands that you need to be careful about
+8.8k Golang : Gorilla web tool kit schema example
+14.3k Golang : Get uploaded file name or access uploaded files
+10.2k Golang : Use regular expression to get all upper case or lower case characters example