Generic hashmap in Go


I’m trying to make a wrapper in go for the map type so that I can add some methods like contains() (this almost makes me miss Java). However, I don’t know if I can do anything like generics in Java.

While almost everything I’ve read says that Go doesn’t have generic types, there must be a better way than writing a separate struct for every single possible combination of structs and values that I’m using.

Here’s what I’m trying to do, even though the code doesn’t work:

func newMap(key interface{}, val interface{}) {
    keytype := key.(type)
    valtype := val.(type)

    return hashmap{map[keytype]valtype}

type hashmap struct {
    hashmap     map[]

Any help/explanation on how to do this would be appreciated.

EDIT: Contains isn’t the only thing I’m trying to replicate, hence the desire to make a "generic" hashmap. replace(), isEmpty(), all that fun stuff as well.


Golang does not have generics, as you say.

But the maps can be declared using your own types, so you don’t necessarily need to write your own “generic” hashmap to use things like “contains” or “is empty”.

Example (assuming some Icon and Colour types already exist, as well as the GetTheIcon function that returns some icon):

// this one will map Icon -> Colour
iconToColours := make(map[Icon]Colour)

myIcon := GetTheIcon()
// second return argument is true if the key was found in the map
_, iconIsContained := iconToColours[myIcon]

// check if the map is empty
isEmpty := (len(iconToColours) == 0)

See more here:

Answered By – eugenioy

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.