[]接口{}的元素类型

element type of []interface{}

如何获取[]interface{}的运行时元素类型?

我尝试了以下测试。

var data interface{}
temp := make([]interface{}, 0)
temp = append(temp, int64(1))
data = temp

elemType := reflect.TypeOf(data).Elem()
switch elemType {
case reflect.TypeOf(int64(1)):
    logger.Infof("type: int64 ")
default:
    logger.Infof("default %v", elemType.Kind()) // "default" is matched in fact

}

[]interface{}的元素类型是interface{}

如果您想要该切片中单个值的动态类型,您需要对该切片进行索引以提取这些值。

data := make([]interface{}, 0)
data = append(data, int64(1))
data = append(data, "2")
data = append(data, false)

typeof0 := reflect.ValueOf(data).Index(0).Elem().Type()
typeof1 := reflect.ValueOf(data).Index(1).Elem().Type()
typeof2 := reflect.ValueOf(data).Index(2).Elem().Type()

https://play.golang.com/p/PVWhIdu1Duz