Okay Go, why was this omitted?

Sean Hoffman
1 min readNov 23, 2022

When checking for the existence of a particular key in Go, the idiomatic way of doing things is this:


salary := make(map[string]uint)
.
.
.

_, ok := salary["Roger Goodell"]

if !ok {
// value wasn't found
salary["Roger Goodell"] = 68000000
} else {
fmt.Println("Roger Goodell is not hurting for cash.")
}

Simple right? Well yes, but also horribly inconvenient. I don’t want to define an in-scope variable to determine if a key exists in the map; sometimes I might want to check and quickly branch off that logic.

To my own little tool-belt I added a KeyExists function:

func KeyExists[K comparable, V any](m map[K]V, value K) (rc bool ) {
_, found := m[value]
rc = found
return rc
}

Now I can check if a key exists and perform logic based on that, and don’t have to squelch return values I’m not interested in:

.
.
if KeyExists( salary, "Roger Goodell" ) {
fmt.Println("Roger Goodell is not hurting for cash")

}

--

--

Sean Hoffman

Software Developer (C++, C#, Go, others), Husband, Father. I eat fried potatoes annually on July 14th.