【发布时间】:2018-11-16 10:23:00
【问题描述】:
我想通过具体的方式比较我的类型。为此,我为每种类型创建了函数MyType.Same(other MyType) bool。
在一些通用函数中,我想检查参数是否具有“相同”函数,如果是则调用它。
我怎样才能以通用的方式为不同的类型做呢?
type MyType struct {
MyField string
Id string // ignored by comparison
}
func (mt MyType) Same(other MyType) bool {
return mt.MyField == other.MyField
}
// MyOtherType... Same(other MyOtherType)
type Comparator interface {
Same(Camparator) bool // or Same(interface{}) bool
}
myType = new(MyType)
_, ok := reflect.ValueOf(myType).Interface().(Comparator) // ok - false
myOtherType = new(myOtherType)
_, ok := reflect.ValueOf(myOtherType).Interface().(Comparator) // ok - false
【问题讨论】:
标签: go