【问题标题】:How to check if a value implements an interface如何检查一个值是否实现了一个接口
【发布时间】: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


【解决方案1】:

类型不满足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 方法,则无需在前面的sn-p 代码中声明Comparator 接口或使用same 函数。例如,以下情况不需要Comparator 接口:

var mt MyType
var other interface{}

eq := mt.Same(other)

【讨论】:

  • 这是更好的答案,Savash。我会删除我的。
  • @TehSphinX,您的回答非常接近,让我找到了与 ThnderCat 发布的相同的解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-12-29
  • 2014-09-02
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多