Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"instanceof" equivalent in Golang

Tags:

go

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

like image 888
Héctor Avatar asked Aug 26 '16 17:08

Héctor


1 Answers

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") } 
like image 169
dave Avatar answered Sep 20 '22 19:09

dave