加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang中的“instanceof”等价物

发布时间:2020-12-16 19:22:41 所属栏目:大数据 来源:网络整理
导读:我有这个结构: type Event interface { Accept(EventVisitor)}type Like struct {}func (l *Like) Accept(visitor EventVisitor) { visitor.visitLike(l)} 如何测试该事件是否为Like实例? func TestEventCreation(t *testing.T) { event,err := New(0) if
我有这个结构:
type Event interface {
    Accept(EventVisitor)
}

type Like struct {
}

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

如何测试该事件是否为Like实例?

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

我明白了:

Type Like is not an expression event Event

您可以将它投射并查看它是否失败:
event,err := New(0)
if err != nil {
    t.Error(err)
}
_,ok := event.(Like)
if !ok {
    t.Error("Assertion error")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读