Search code examples
goreflect

element type of []interface{}


How to get the runtime element type of []interface{}?

I tried the following test.

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

}

Solution

  • The element type of []interface{} is interface{}.

    If you want the dynamic type of individual values in that slice you'll need to index into that slice to pull those values out.

    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