相关疑难解决方法(0)

如果结构体具有参数实现接口的方法,则该结构体不实现接口

我有一个包,其中有两个接口

package main

type A interface {
    Close()
}

type B interface {
    Connect() (A, error)
}
Run Code Online (Sandbox Code Playgroud)

我还有两个实现这些接口的结构

type C struct {
}

func (c *C) Close() {

}

type D struct {
}

func (d *D) Connect() (*C, error) {
    c := new(C)
    return c, nil
}
Run Code Online (Sandbox Code Playgroud)

接下来我有一个函数,它作为参数需要一个实现接口 B 的对象

func test(b B) {
}
Run Code Online (Sandbox Code Playgroud)

最后,在 main() 函数中我创建了 D 结构对象并想要调用 test() 函数

func main() {
    d := new(D)
    test(d)
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试构建该包,则会出现错误。

无法在测试参数中使用 d(类型 *D)作为类型 B:*D 未实现 B(Connect 方法的类型错误)有 Connect()(*C,错误)想要 …

struct interface go

3
推荐指数
1
解决办法
3847
查看次数

标签 统计

go ×1

interface ×1

struct ×1