Golang 中如何获取interface参数的类型?
执行使用以下语句:
fmt.Println("type:", v.(type))
提示错误:
use of .(type) outside type switch
正确的使用方法是必须在switch case中。
举例如下:
package main
import (
"fmt"
)
func main() {
CheckType("tow", 88, "three")
}
func CheckType(args ...interface{}) {
for _,v := range args {
switch v.(type) {
case int:
fmt.Println("type:int, value:", v)
case string:
fmt.Println("type:string, value:", v)
default:
fmt.Println("type:unkown,value:",v)
}
}
}
编译,执行
$ go build arm.go
$ ./arm
结果:
type:string, value: tow
type:int, value: 88
type:string, value: three