Go中所有的类型都可以被转化成interface{},通常在传入可变参数中的API中,可变参数的类型就是interface{}。
func typeConversion(strs ...interface{}) (ret []string) {
for _, s := range strs {
ret = append(ret, string(s))
}
}
上述代码是不能运行的,错误为:
cannot convert s (type interface {}) to type string: need type assertion
意思是在类型转化的过程中,需要进行Type Assertion。
简单的Assertion如下:
var a interface{}
a = "string" //本行注释会导致panic
fmt.Println(a.(string))
上述方式Assertion失败的时候会导致panic。故可以使用下面的方式进行Assertion。
func testAssertion(a interface{}) (err error) {
val, ok := a.(string)
if !ok {
fmt.Println("not string")
return fmt.Errorf("nnot string")
}
fmt.Println(val)
return nil
}
这样可以通过ok来判断Assertion的结果。
还可以通过switch的方式进行判断。
func testAssertionBySwitch(a interface{}) {
switch a.(type) {
case bool:
fmt.Println("bool")
case string:
fmt.Println("string")
case int:
fmt.Println("int")
default:
fmt.Println("cannot judged")
}
}