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

1
  • 1
    Don't use pointers to interfaces. Replace Subscribe(EventType, *Handler) with Subscribe(EventType, Handler), etc. stackoverflow.com/questions/44370277/… Commented Feb 23, 2022 at 9:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.