dpg78570 2018-09-19 00:21
浏览 55
已采纳

如何在运行时指定类型的元素数组

I am trying to create a array of elements with a type known only at the run time (a pkg API gets to retrieve elements in json and convert to struct). I have a helper function something like below, which takes an interface as a param and trying to get the type of interface while calling make.

golang compiler doesn't seems to like it.

var whatAmI = func(i interface{}) { 
        a := reflect.TypeOf(i)

        //var typ reflect.Type = a

        b := make (a, 10)    //10 elem with type of i

        //b := new (typ)
        fmt.Printf ("a: %v b: %v", a, b)
}

prog.go:21:14: a is not a type

I tried various combinations of reflects but no help so far. This seems to me can be a common problem to run in to. How can I solve/workaround this?

  • 写回答

2条回答 默认 最新

  • dongying7667 2018-09-19 01:21
    关注

    Get the type for a slice given a value of the element type, v:

    sliceType := reflect.SliceOf(reflect.TypeOf(v))
    

    Create a slice with length and capacity (both 10 here).

    slice:= reflect.MakeSlice(sliceType, 10, 10)
    

    Depending on what you are doing, you may want to get the actual slice value by calling Interface() on the reflect.Value:

    s := slice.Interface()
    

    Run it on the playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源