Check if a key exists in a Go map using the comma-ok idiom to safely retrieve the value and a boolean status.
Use the comma-ok idiom to check if a key exists in a map by assigning the value and a boolean to two variables. If the key exists, the boolean is true; if not, it is false.
m := map[string]int{"apple": 1, "banana": 2}
if val, ok := m["apple"]; ok {
fmt.Println("Key exists, value:", val)
} else {
fmt.Println("Key does not exist")
}
Checking if a key exists in a map in Go lets you safely verify if a specific item is in a list of key-value pairs without causing your program to crash. It works like asking a librarian if a book exists on the shelf; they either hand you the book (value) and say yes, or they say no and give you nothing. You use this whenever you need to verify data is present before trying to use it.