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
+21k Golang : Strings to lowercase and uppercase example
+5.8k Golang : How to convert strange string to JSON with json.MarshalIndent
+7.8k Golang : Use regular expression to get all upper case or lower case characters example
+5.3k Golang : How to handle file size larger than available memory panic issue
+4.3k Golang : Generate multiplication table from an integer example
+26.9k Golang : bufio.NewReader.ReadLine to read file line by line
+30.6k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+6.2k Golang : Qt splash screen with delay example
+5.3k Golang : Transform lisp or spinal case to Pascal case example
+5.4k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+3.4k Golang : A program that contain another program and executes it during run-time
+4.5k Golang : Selection sort example