英文:
golang compiler errors when trying to use interface method
问题
我正在构建一个简单的可观察和处理程序包:
package observe
type EventType string
type Event struct {
Type EventType
Data interface{}
}
type Observable interface {
Subscribe(EventType, *Handler)
Unsubscribe(EventType, *Handler)
Emit(EventType, interface{})
}
type Handler interface {
Handle(*Event)
}
我创建了以下代码来使用该包:
...
type ObservableMock struct {
subscribers map[EventType][]*Handler
}
func (om *ObservableMock) Emit(et EventType, data interface{}) {
event := &Event{
Type: et,
Data: data,
}
for _, handler := range om.subscribers[et] {
// 错误发生在这里
handler.Handle(event)
}
}
...
当我尝试使用handler.Handle(event)
时,我得到了这个错误:handler.Handle undefined (type *Handler has no field or method Handle)
。
这对我来说没有意义。据我理解,根据golang的接口规范,它应该可以工作,因为任何Handler
接口的实现都将具有Handle(*Event)
方法。
英文:
I am building a simple observable and handler package:
package observe
type EventType string
type Event struct {
Type EventType
Data interface{}
}
type Observable interface {
Subscribe(EventType, *Handler)
Unsubscribe(EventType, *Handler)
Emit(EventType, interface{})
}
type Handler interface {
Handle(*Event)
}
I created this to use the package:
...
type ObservableMock struct {
subscribers map[EventType][]*Handler
}
func (om *ObservableMock) Emit(et EventType, data interface{}) {
event := &Event{
Type: et,
Data: data,
}
for _, handler := range om.subscribers[et] {
// ERROR HAPPENS HERE
handler.Handle(event)
}
}
...
When I try to use handler.Handle(event)
I get this: handler.Handle undefined (type *Handler has no field or method Handle)
It doesn't make sense to me. As far as I understand golang interfaces it should work, because any implementation of the Handler
interface is going to have Handle(*Event)
.
答案1
得分: 1
问题是,实际上,当运行go build
时,Visual Code并没有给出与编译器相同的错误。
真正的错误是:observe/observe_test.go:34:11: handler.Handle undefined (type *Handler is pointer to interface, not interface)
通过对处理程序进行解引用,可以很容易地解决这个问题:(*handler).Handle(event)
。
英文:
The problem is that Visual Code is actually not giving the same error as the compiler when running go build
.
The real error is: observe/observe_test.go:34:11: handler.Handle undefined (type *Handler is pointer to interface, not interface)
This could be easily solved by dereferencing the handler: (*handler).Handle(event)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论