check if a key exists in a map with a key of type int in go

To check if a key of type int exists in a map in go, you can use the _, ok := map[key] syntax.

The following code snippet demonstrates how to check if a key of type int exists in a map in go:

main.go
myMap := make(map[int]string)

// Add key-value pairs to map
myMap[1] = "apple"
myMap[2] = "banana"
myMap[3] = "cherry"

// Check if key 2 exists
if _, ok := myMap[2]; ok {
    fmt.Println("Key 2 exists in map")
} else {
    fmt.Println("Key 2 does not exist in map")
}

// Check if key 4 exists
if _, ok := myMap[4]; ok {
    fmt.Println("Key 4 exists in map")
} else {
    fmt.Println("Key 4 does not exist in map")
}
420 chars
21 lines

In the code snippet above, we create a map myMap with integer keys and string values. We add some key-value pairs to the map and then check if a few keys exist using the if _, ok := myMap[key]; ok syntax. If the key exists in the map, the value of ok will be true, otherwise it will be false.

related categories

gistlibby LogSnag