2

I have started to use Golang and know that custom structs can be used as keys in maps. But I wanted to know if it is possible to explicitly specify how my map can differenciate between the keys (similar to Java where we use hashcode() and equals()). Lets say we have:

type Key struct {
   Path, Country string
}

If I want to specify that only the Path attribute of struct Key be used to differentiate between keys in a map, how do I do that?

Sudatta
  • 73
  • 3
  • 8
  • try this? https://stackoverflow.com/questions/24534072/how-to-compare-struct-slice-map-are-equal Please do some searching around this site. Chances are, your questions may have already been answered before. Otherwise, welcome to SO! – S.R.I Mar 27 '18 at 22:00
  • 2
    If you only want `Path` to be used to differentiate between keys in a map, shouldn't `Path` be the key instead of the struct? – Andy Schweig Mar 27 '18 at 22:12

1 Answers1

2

map keys may be of any type that is comparable. The language spec defines this precisely, but in short, comparable types are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types. Notably absent from the list are slices, maps, and functions; these types cannot be compared using ==, and may not be used as map keys. https://blog.golang.org/go-maps-in-action

But you can implement hashCode(), that takes struct as argument and returns string. Then use this string as key in map.

for instance:

type Key struct {
  Path, City, Country string
}

func (k Key) hashCode() string {
   return fmt.Sprintf("%s/%s", k.Path, k.City) //omit Country in your hash code here
}


func main(){
  myMap := make(map[string]interface{})

  n := Key{Path: "somePath", City:"someCity", Country:"someCountry"}
  myMap[n.hashCode()] = "someValue"
}
trierra
  • 279
  • 1
  • 2
  • 8