Go map with user-defined key with user-defined equality?

前端 未结 2 2099
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 12:26

Suppose I have a struct type in Go that I want to use as a key in a map, but I don\'t want to use Go\'s builtin equality operation. What\'s the best way to build s

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 13:24

    This is not possible in Go. There is no operator overloading or 'Equality' method you can override (due to not inheriting from a common base class like in .NET which your example reminds me of). This answer has more information on equality comparisons if you're interested; Is it possible to define equality for named types/structs?

    As mentioned in the comments if you want to make something like this work I would recommend using a property on the object as a key. You can define equality based on how you set the value of that property (like it could be a checksum of the objects bytes or something if you're looking for memberwise equality).

提交回复
热议问题