我想通过具体的方式比较我的类型。为此,我为每种类型创建函数 MyType.Same(other MyType) bool
。
在一些通用函数中,我想检查参数是否有一个函数“Same”,如果是则调用它。
我怎样才能以通用的方式为不同的类型做到这一点?
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
最佳答案
类型不满足Comparator
接口(interface)。这些类型有一个 Same
方法,但这些方法没有参数类型 Comparator
。参数类型必须匹配以满足接口(interface)。
更改方法和接口(interface)以采用相同的参数类型。使用类型断言来检查接收者和参数是否具有相同的类型,并获取与接收者类型相同的参数。
type Comparator interface {
Same(interface{}) bool
}
func (mt MyType) Same(other interface{}) bool {
mtOther, ok := other.(MyType)
if !ok {
return false
}
return return mt.MyField == mtOther.MyField
}
使用以下比较两个值:
func same(a, b interface{}) bool {
c, ok := a.(Comparator)
if !ok {
return false
}
return c.Same(b)
}
如果应用程序使用的类型具有Compare
方法,则无需声明Comparator
接口(interface)或使用same
函数在前面的代码片段中。例如,以下不需要 Comparator
接口(interface):
var mt MyType
var other interface{}
eq := mt.Same(other)
关于go - 如何检查一个值是否实现了一个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50725367/