Go type-error:struct没有实现接口

时间:2018-01-10 18:19:13

标签: testing go mocking

// BEGIN: external library

type realX struct {}

type realY struct {}

func (realX) Do() realY {
  return realY{}
}

// END

type A struct {
  a myX
}

type myY interface {}

type myX interface {
  Do() myY
}

func foo (arg1 myY) {
}

func main() {
    foo(realY{})
    x := A{realX{}}
    fmt.Println("Hello, playground")
}

我明白了:

cannot use realX literal (type realX) as type myX in field value:
    realX does not implement myX (wrong type for Do method)
        have Do() realY
        want Do() myY

从它的外观来看,realY实现了myY,为什么我不能这样做呢?这使得无法干净地编写模拟单元测试。

1 个答案:

答案 0 :(得分:6)

不,它没有实现myY,因为错误明确指出:

realX does not implement myX (wrong type for Do method)
    have Do() realY
    want Do() myY

方法签名必须与完全匹配才能实现接口的类型。方法签名不匹配 - 返回类型不同。如果realY实现myY,则无关紧要;签名不一样。