pointers - Go:接口(interface)类型映射比较

标签 pointers go

假设我有很多不同的结构类型,它们都满足一个接口(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)的结构使用作为指针接收器 的函数来实现,因为我经常传递它们,没有指针就很笨重。

通常,我想在 food1food2 之间进行比较,因此我构建了看起来像 foodmap := map[Food]bool。我真正想检查的是底层结构是否相同。但是,因为它总是满足接口(interface)的指针,所以如果我创建两个相同类型的 fruitvegetable,我无法使用映射或列表进行相等性或存在性测试>,例如。

比较 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 like map[FoodKey], where any struct that satsifies Food provides a FoodKey() comparisonStruct method that returns a struct meant strictly for comparison?

我怀疑这是一种更好的方法,考虑到:

关于pointers - Go:接口(interface)类型映射比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25180509/

相关文章:

c - C 中的指针——加 1

c - 为什么这个程序有意外的指针值?

C++ delete - 它删除了我的对象,但我仍然可以访问数据?

go - 有没有办法一次构建多个基于 Go 模块的项目?

Golang MongoDB 错误 : result argument must be a slice address - (Arrays)

variables - Go 声明中的 "_,"(下划线逗号)是什么?

c - 理解C中的指针

c++ - C++ 类指针的动机

go - 为什么kubetest不按照说明安装?

go - 如何检查 go template 是否使用了所有模板数据