[英]How to check if a value implements an interface
我想通過特定方式比較我的類型。 為此,我為每種類型創建函數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
接口。 這些類型具有Same
方法,但是這些方法沒有參數類型Comparator
。 參數類型必須匹配才能滿足接口要求。
更改方法和接口以采用相同的參數類型。 使用類型斷言來檢查接收方和參數是否具有相同的類型,並獲取與接收方類型相同的參數。
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
接口或在前面的代碼片段中使用same
函數。 例如,對於以下情況,不需要Comparator
接口:
var mt MyType
var other interface{}
eq := mt.Same(other)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.