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

huangapple go评论97阅读模式
英文:

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)
}

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

huangapple
  • 本文由 发表于 2016年3月19日 02:30:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/36091801.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定