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
+9.4k Golang : Resumable upload to Google Drive(RESTful) example
+7.6k Findstr command the Grep equivalent for Windows
+6.1k Golang : Join lines with certain suffix symbol example
+10.1k Golang : Allow Cross-Origin Resource Sharing request
+17.2k How to enable MariaDB/MySQL logs ?
+7.2k Gogland : Single File versus Go Application Run Configurations
+6.5k Golang : Pat multiplexer routing example
+15.9k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+10.1k Golang : Create matrix with Gonum Matrix package example
+12.2k Golang : Transform comma separated string to slice example
+7.1k Android Studio : AlertDialog to get user attention example