-1

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

}
Hel
  • 305
  • 5
  • 14
  • so, what is your question? So you wanted to ask that your desire output is `type: int64` but you are getting `default ...` ? – Kamol Hasan Aug 06 '19 at 04:17
  • @KamolHasan Yes,I would think the element type is the real data runtime type, instead of interface. – Hel Aug 06 '19 at 04:54

1 Answers1

1

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

mkopriva
  • 35,176
  • 4
  • 57
  • 71