英文:
Avoid using type assertions in the branches of a type switch
问题
我在Go语言中使用了类型开关(type switches),例如下面的代码:
switch question.(type) {
case interfaces.ComputedQuestion:
handleComputedQuestion(question.(interfaces.ComputedQuestion), symbols)
case interfaces.InputQuestion:
handleInputQuestion(question.(interfaces.InputQuestion), symbols)
}
有没有办法在将问题传递给另一个函数之前,避免在case内部断言(assert)问题的类型?
英文:
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?
答案1
得分: 7
是的,将类型切换的结果赋值给变量question将得到断言的类型。
switch question := question.(type) {
case interfaces.ComputedQuestion:
handleComputedQuestion(question, symbols)
case interfaces.InputQuestion:
handleInputQuestion(question, symbols)
}
http://play.golang.org/p/qy0TPhypvp
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论