-1

如何获取运行时元素类型[]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

}
4

1 回答 1

1

的元素类型[]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

于 2019-08-06T04:50:17.507 回答