尝试使用接口方法时,Golang编译器报错。

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

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).

huangapple
  • 本文由 发表于 2022年2月23日 06:59:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/71229364.html
匿名

发表评论

匿名网友

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

确定