结构体即使具有相同的函数,也不能实现接口

huangapple go评论90阅读模式
英文:

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()
}

huangapple
  • 本文由 发表于 2016年1月22日 00:24:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/34928998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定