"instanceof" equivalent in Golang

Issue

I have these structs:

type Event interface {
    Accept(EventVisitor)
}

type Like struct {
}

func (l *Like) Accept(visitor EventVisitor) {
    visitor.visitLike(l)
}

How can I test that event is a Like instance?

func TestEventCreation(t *testing.T) {
    event, err := New(0)
    if err != nil {
        t.Error(err)
    }
    if reflect.TypeOf(event) != Like {
        t.Error("Assertion error")
    }
}

I get:

Type Like is not an expression event Event

Solution

You could just do a type assertion and see if it fails:

event, err := New(0)
if err != nil {
    t.Error(err)
}
_, ok := event.(Like)
if !ok {
    t.Error("Assertion error")
}

Answered By – dave

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.