避免在类型开关的分支中使用类型断言 [英] Avoid using type assertions in the branches of a type switch

查看:45
本文介绍了避免在类型开关的分支中使用类型断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Go中使用类型开关,例如以下内容:

I use type switches in Go, e.g. the following one:

switch question.(type) {
case interfaces.ComputedQuestion:
    handleComputedQuestion(question.(interfaces.ComputedQuestion), symbols)
case interfaces.InputQuestion:
    handleInputQuestion(question.(interfaces.InputQuestion), symbols)
}

有没有一种方法可以防止在将问题传递给另一个函数之前必须断言案件中的问题类型?

Is there a way to prevent that I have to assert the type of question inside the case before I can pass it to another function?

推荐答案

是的,分配类型切换的结果将为您提供断言的类型

Yes, assigning the result of the type switch will give you the asserted type

switch question := question.(type) {
case interfaces.ComputedQuestion:
    handleComputedQuestion(question, symbols)
case interfaces.InputQuestion:
    handleInputQuestion(question, symbols)
}

http://play.golang.org/p/qy0TPhypvp

这篇关于避免在类型开关的分支中使用类型断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆