英文:
Struct doesn't implement interface even if it has the same functions
问题
我不知道以下编译错误的原因。我会很感激任何帮助。
./router.go:190: 无法将listener(类型为webhooklistener.MyListener)作为webhook.Listener类型的字段值使用:
webhooklistener.MyListener未实现webhook.Listener(缺少webhook.handle方法)
具有webhooklistener.handle()
期望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} // 编译错误
英文:
I don't know what is the reason of following compilation error. I will appreciate any help.
./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()
Client:
package webhook
type Listener interface {
handle()
}
type Client struct {
Listener Listener
}
Listener:
package webhooklistener
type MyListener struct {
}
func (ll MyListener) handle() {
}
Router:
listener := webhooklistener.MyListener{}
client := webhook.Client{listener} // COMPILATION ERROR
答案1
得分: 16
webhook.Listener
的唯一方法是未导出的,因此只有该包中的标识符才能实现它。如果你希望其他包中的类型能够实现它,你需要将其导出:
type Listener interface {
Handle()
}
英文:
webhook.Listener
's only method is unexported, so only identifiers in that package can implement it. If you want types in other packages to be able to implement it, you need to make it exported:
type Listener interface {
Handle()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论