猿问

避免在类型切换的分支中使用类型断言

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


switch question.(type) {

case interfaces.ComputedQuestion:

    handleComputedQuestion(question.(interfaces.ComputedQuestion), symbols)

case interfaces.InputQuestion:

    handleInputQuestion(question.(interfaces.InputQuestion), symbols)

}

有没有办法防止我必须在案例中声明问题类型,然后才能将其传递给另一个函数?


慕仙森
浏览 167回答 1
1回答

慕标5832272

是的,分配类型开关的结果会给你断言的类型switch question := question.(type) {case interfaces.ComputedQuestion:    handleComputedQuestion(question, symbols)case interfaces.InputQuestion:    handleInputQuestion(question, symbols)}http://play.golang.org/p/qy0TPhypvp
随时随地看视频慕课网APP

相关分类

Go
我要回答