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
+17.7k Golang : convert int to string
+32.9k Golang : Integer is between a range
+14k Golang : Force download file example
+14.8k Golang : Get sub string example
+6.3k Golang : Scanf function weird error in Windows
+8.3k Golang : How to get ECDSA curve and parameters data?
+3.9k Which content-type(MIME type) to use for JSON data
+4.9k Golang : Find change in a combination of coins example
+5.7k Golang : Warp text string by number of characters or runes example
+26.8k Golang : Connect to database (MySQL/MariaDB) server
+35.1k Golang : Convert date or time stamp from string to time.Time type
+8k Golang : Generate random Chinese, Japanese, Korean and other runes