假设我有很多不同的结构类型,它们都满足一个接口(interface)Food
。
type Food interface {
Name() string
Tastiness() int
}
type fruit struct {
species string
numSeeds int
}
type vegetable struct {
commonName string
weight int
}
func (f *fruit) Name() string { return f.species }
func (f *fruit) Tastiness() int { return 100 - f.numSeeds }
func (v *vegetable) Name() string { return v.commonName }
func (v *vegetable) Tastiness() int { return 1 }
满足Food
接口(interface)的结构使用作为指针接收器
的函数来实现,因为我经常传递它们,没有指针就很笨重。
通常,我想在 food1
和 food2
之间进行比较,因此我构建了看起来像 foodmap := map[Food]bool的 map
。我真正想检查的是底层结构是否相同。但是,因为它总是满足接口(interface)的指针,所以如果我创建两个相同类型的 fruit
或 vegetable
,我无法使用映射或列表进行相等性或存在性测试>,例如。
比较 Food
与 不 的最佳方法是使用 map[Food]bool
而是使用类似 map[ FoodKey]
,其中任何满足 Food
的结构都提供了一个 FoodKey() comparisonStruct
方法,该方法返回一个严格用于比较的结构?
最佳答案
Is the best way to compare Foods to not use
map[Food]bool
and instead use something likemap[FoodKey]
, where any struct that satsifies Food provides aFoodKey() comparisonStruct
method that returns a struct meant strictly for comparison?
我怀疑这是一种更好的方法,考虑到:
- 比较界面慢(issue 6105)
- (假设 comparison operators 已定义:参见 Map Types)
- 使用
Equaler
(如 this thread )并不容易 - 您可能需要区分您正在比较的接口(interface)实例中包含的实际类型。
关于pointers - Go:接口(interface)类型映射比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25180509/