简体   繁体   English

如何检查值是否实现接口

[英]How to check if a value implements an interface

I want to compare my type by the specific way. 我想通过特定方式比较我的类型。 For this purpose, I create the function MyType.Same(other MyType) bool for each type. 为此,我为每种类型创建函数MyType.Same(other MyType) bool

In some generic function, I want to check if the parameter has a function "Same" and invoke it if yes. 在某些通用函数中,我想检查参数是否具有函数“ Same”,如果是,则调用它。

How can I do it in a generic way for different types? 如何以通用方式针对不同类型执行此操作?

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

The types do not satisfy the Comparator interface. 这些类型不满足Comparator接口。 The types have a Same method, but those methods do not have argument type Comparator . 这些类型具有Same方法,但是这些方法没有参数类型Comparator The argument types must match to satisfy an interface. 参数类型必须匹配才能满足接口要求。

Change the the methods and interface to take the same argument type. 更改方法和接口以采用相同的参数类型。 Use a type assertion to check that receiver and argument have the same type and to get argument as the receiver's type. 使用类型断言来检查接收方和参数是否具有相同的类型,并获取与接收方类型相同的参数。

 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
}

Use the following to compare two values: 使用以下内容比较两个值:

func same(a, b interface{}) bool {
  c, ok := a.(Comparator)
  if !ok {
     return false
  }
  return c.Same(b)
}

If the types the application works with have the Compare method, then there's no need to declare the Comparator interface or use the same function in the previous snippet of code. 如果应用程序使用的类型具有Compare方法,则无需声明Comparator接口或在前面的代码片段中使用same函数。 For example, the Comparator interface is not required for the following: 例如,对于以下情况,不需要Comparator接口:

var mt MyType
var other interface{}

eq := mt.Same(other)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM