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

edw*_*dmp 1 go

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

switch question.(type) {
case interfaces.ComputedQuestion:
    handleComputedQuestion(question.(interfaces.ComputedQuestion), symbols)
case interfaces.InputQuestion:
    handleInputQuestion(question.(interfaces.InputQuestion), symbols)
}
Run Code Online (Sandbox Code Playgroud)

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

Jim*_*imB 7

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

switch question := question.(type) {
case interfaces.ComputedQuestion:
    handleComputedQuestion(question, symbols)
case interfaces.InputQuestion:
    handleInputQuestion(question, symbols)
}
Run Code Online (Sandbox Code Playgroud)

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

  • @edwardmp,这在[规范](https://golang.org/ref/spec#Switch_statements)中有解释."有效的Go"[已涵盖](https://golang.org/doc/effective_go.html#type_switch)以及[wiki关于交换机的文章](https://github.com/golang/go) /维基/开关).所以我真的建议你读一本关于Go的书("Effective Go"就可以开始了). (4认同)