dongyingtang3803 2018-06-06 16:34
浏览 5
已采纳

如何检查值是否实现接口

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.

In some generic function, I want to check if the parameter has a function "Same" and invoke it if yes.

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
  • 写回答

1条回答 默认 最新

  • duanqiongchong0354 2018-06-06 17:01
    关注

    The types do not satisfy the Comparator interface. The types have a Same method, but those methods do not have argument type 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. For example, the Comparator interface is not required for the following:

    var mt MyType
    var other interface{}
    
    eq := mt.Same(other)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭