invalid operation: test (variable of type xxx) is not an interface
//var s = x.(T)
var test interface{} = "hello world"
testStr := test.(string)
如果斷言類型成立,則表達式返回值就是T 類型的x,如果斷言失敗就會觸發panic。
s, ok := x.(T)
是ok 會返回是否斷言成功不會出現panic,ok 就表示是否是成功了。
switch 的斷言方法
go 語法種還提供了另外一種類型switch 的斷言方法。
switch i := x.(type) {
case nil:
print("x is nil")
case int:
print(i)
case float64:
print(i)
case func(int) float64:
printFunction(i)
case bool, string:
print("type is bool or string")
default:
print("unknown type")
}