Is it possible to define equality for named types/structs?

Bill DeRose picture Bill DeRose · Dec 1, 2013 · Viewed 26.2k times · Source

After reading a related question about using slices in maps, I became curious about equality in Go.

I know it's possible to override the equals method of a Java Object. Is there a similar way to define how Go checks user defined types/structs for equality? If so, there would be a workaround for the issue referenced above. I thought using interface{} values might offer a solution but I received the error message panic: runtime error: hash of unhashable type []int.

Answer

Volker picture Volker · Dec 2, 2013

No, this is not user-definable. Go has strict rules what counts as equal, and even what is comparable which itself is based on assignability. Take a look at the Comparison operators section of the spec.