1

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

Vitor Falcão
  • 1,007
  • 1
  • 7
  • 18
  • 1
    Don't use pointers to interfaces. Replace `Subscribe(EventType, *Handler)` with `Subscribe(EventType, Handler)`, etc. https://stackoverflow.com/questions/44370277/type-is-pointer-to-interface-not-interface-confusion – Peter Feb 23 '22 at 09:32

1 Answers1

1

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

Vitor Falcão
  • 1,007
  • 1
  • 7
  • 18