避免在类型开关的分支中使用类型断言

时间:2016-03-18 18:30:03

标签: go

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

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

有没有办法防止我必须先在案例中断言问题类型才能将其传递给另一个函数?

1 个答案:

答案 0 :(得分:7)

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

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

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