dongyi2425 2019-08-06 02:08
浏览 267
已采纳

[] 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

}
  • 写回答

1条回答 默认 最新

  • doulianxing4015 2019-08-06 04:50
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器