go - struct 没有实现接口(interface),即使它具有相同的功能

标签 go

我不知道出现以下编译错误的原因是什么。我将不胜感激。

./router.go:190: cannot use listener (type webhooklistener.MyListener) as type webhook.Listener in field value:
    webhooklistener.MyListener does not implement webhook.Listener (missing webhook.handle method)
        have webhooklistener.handle()
        want webhook.handle()

客户:

package webhook

type Listener interface {
    handle()
}

type Client struct {
    Listener Listener
}

听众:

package webhooklistener

type MyListener struct {
}

func (ll MyListener) handle() {

}

路由器:

listener := webhooklistener.MyListener{}
client := webhook.Client{listener} // COMPILATION ERROR

最佳答案

webhook.Listener 的唯一方法是未导出的,因此只有该包中的标识符才能实现它。如果您希望其他包中的类型能够实现它,则需要将其导出:

type Listener interface {
    Handle()
}

关于go - struct 没有实现接口(interface),即使它具有相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928998/

相关文章:

performance - Go 是如何编译得这么快的?

mongodb - 如何在golang中向mongodb插入一个json对象数组

go - 简单 HTTPS 请求 : Golang returns 505, Python 和 Chrome 工作

去wait4函数

go - Golang-为什么总是ItoA在返回字符串时删除初始0

go - 如何使GtkModelButton发出点击信号而不是GAction?

go - 具有等待功能的链接命令

mongodb - 在 mongodb golang 中保存 session

regex - 使用正则表达式解析 Apache 日志文件

xml - 在 GO 中创建一个流来读取一个巨大的字符串