我在Go中使用类型开关,例如以下一个:
switch question.(type) {
case interfaces.ComputedQuestion:
handleComputedQuestion(question.(interfaces.ComputedQuestion), symbols)
case interfaces.InputQuestion:
handleInputQuestion(question.(interfaces.InputQuestion), symbols)
}
有没有办法防止我必须先在案例中断言问题类型才能将其传递给另一个函数?
答案 0 :(得分:7)
是的,分配类型开关的结果将为您提供断言类型
switch question := question.(type) {
case interfaces.ComputedQuestion:
handleComputedQuestion(question, symbols)
case interfaces.InputQuestion:
handleInputQuestion(question, symbols)
}