言語タイプアサーションとタイプスイッチを実行します
Go Language Type Assertion
最初のタイプのアサーションとタイプの切り替えは、インターフェイス{}にのみ適用でき、他のタイプには適用できません。
func main() { var v string = 'hello' // var v interface{} = “hello' s, ok := v.(string) fmt.Println('s=',s,',ok=',ok) switch v.(type) { case string: fmt.Println('This is a string') case int: fmt.Println('This is a int') default: fmt.Println('This is default') } }
次のコンパイルエラーが発生します。
$ go build # main ./main.go:XX: invalid type assertion: v.(string) (non-interface type string on left) ./main.go:XX: cannot type switch on non-interface value v (type string)
タイプアサーション
文法 element.(T)
例
package main import 'fmt' func main() { var i interface{} = 'hello' s := i.(string) fmt.Println(s) f := i.(float64) // panic fmt.Println(f) }
演算結果:
hello panic: interface conversion: interface {} is string, not float64 goroutine 1 [running]: main.main() /$GOPATH/src/main/main.go:11 +0x192
- iからstringへの型アサーションは成功し、 'hello'に等しいsを返します。
- iはfloat64型ではないため、iからfloat64への型アサーションは失敗し、パニックが発生します。
もちろん、アサーションの失敗は問題ではありませんが、パニックになることはありません。解決策は次のとおりです。
package main import 'fmt' func main() { var i interface{} = 'hello' s := i.(string) fmt.Println(s) f, ok := i.(float64) // panic if ok { fmt.Println(f) } else { fmt.Println('not a float64') } }
結果を再度実行します。
$ go build && ./main hello not a float64
アサーションが失敗すると、okはfalseを返すため、パニックにはなりません。
タイプスイッチ
vはinterface {}として定義する必要があることに注意してください。そうしないと、コンパイルが失敗します。
var v interface{} = 'hello' switch v.(type) { case string: fmt.Println('This is a string') case int: fmt.Println('This is a int') default: fmt.Println('This is default') }
型アサーションと型切り替えは、C ++のポリモーフィック型間の変換と判断に非常に似ています。