如果结构具有参数实现接口的功能,则结构不实现接口 [英] Struct does not implement interface if it has a function which parameter implement interface
问题描述
我有一个包含两个接口的程序包
I have a package in which I have two interfaces
package main
type A interface {
Close()
}
type B interface {
Connect() (A, error)
}
我还有两个实现这些接口的结构
I have also two structures which implements these interfaces
type C struct {
}
func (c *C) Close() {
}
type D struct {
}
func (d *D) Connect() (*C, error) {
c := new(C)
return c, nil
}
接下来,我有一个函数,该函数需要一个实现接口B的对象作为参数
Next I have a function which as a parameter wants an object which implements interface B
func test(b B) {
}
最后,在main()函数中,我创建了D结构对象并想调用test()函数
Finally, at the main() function I create D structure object and want to call test() function
func main() {
d := new(D)
test(d)
}
如果我尝试构建该软件包,则会出错.
If I try to build that package I have an error.
不能在测试参数中使用d(* D型)作为B型: * D没有实现B(Connect方法的类型错误) 有Connect()(* C,错误) 想要Connect()(A,错误)
cannot use d (type *D) as type B in argument to test: *D does not implement B (wrong type for Connect method) have Connect() (*C, error) want Connect() (A, error)
这是我的代码的简单示例,其中我使用外部包并希望模拟结构进行测试.使用接口代替类型有什么解决方案吗?
It is simple example of my code where I use external package and want to mock structures for tests. Is it any solution to use interfaces instead of types?
推荐答案
Connect
方法的返回类型应为A
而不是*C
.
The returned type for your Connect
method should be A
and not *C
.
您定义Connect
方法的方式是它应该返回接口,而不是特定类型.您仍然可以返回*C
,因为它实现了A
接口.
The way you defined the Connect
method is that it should return an interface, not a specific type. You will still be able to return *C
as it implements the A
interface.
package main
type A interface {
Close()
}
type B interface {
Connect() (A, error)
}
type C struct {
}
func (c *C) Close() {
}
type D struct {
}
func (d *D) Connect() (A, error) {
c := new(C)
println("successfully created new C:", c)
return c, nil
}
func test(b B) {
b.Connect()
}
func main() {
d := new(D)
test(d)
}
输出
成功创建了新的C:0xe28f0
successfully created new C: 0xe28f0
这篇关于如果结构具有参数实现接口的功能,则结构不实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!