How to Check If a Key Exists in a Map in Go

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")
}