2016-03-18 8 views
0

私はGoでタイプスイッチを使用しています。 1を次タイプスイッチのブランチでタイプアサーションを使用しないでください。

switch question.(type) { 
case interfaces.ComputedQuestion: 
    handleComputedQuestion(question.(interfaces.ComputedQuestion), symbols) 
case interfaces.InputQuestion: 
    handleInputQuestion(question.(interfaces.InputQuestion), symbols) 
} 

私は別の関数に渡すことができます前に、ケース内の質問の種類を主張していることを防ぐための方法はありますか?

答えて

4

はい、型スイッチの結果を代入すると、あなたにアサートタイプ

switch question := question.(type) { 
case interfaces.ComputedQuestion: 
    handleComputedQuestion(question, symbols) 
case interfaces.InputQuestion: 
    handleInputQuestion(question, symbols) 
} 

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

+0

素晴らしいジム、行の2つの答えが得られます。良い方法がなければならないことを知っていた。本当にありがとう! – edwardmp

+2

@edwardmpについては、[spec](https://golang.org/ref/spec#Switch_statements)で説明しています。 「有効な行為」(https://golang.org/doc/effective_go.html#type_switch)も同様に「スイッチに関するwikiの記事」(https://github.com/golang/go)も同様です。/wiki/Switch)。だから私は本当にあなたがGoについての本を読むことをお勧めします( "Effective Go"はちょうどいいです)。 – kostix

関連する問題