doubiaode0460 2017-05-26 09:20
浏览 2
已采纳

golang反映价值的切片

fmt.Println(v.Kind())
fmt.Println(reflect.TypeOf(v))

How can I find out the type of the reflect value of a slice?

The above results in

v.Kind = slice
typeof = reflect.Value

When i try to Set it will crash if i create the wrong slice

t := reflect.TypeOf([]int{})
s := reflect.MakeSlice(t, 0, 0)
v.Set(s)

For example []int{} instead of []string{} so I need to know the exact slice type of the reflect value before I create one.

  • 写回答

1条回答 默认 最新

  • duanjiao5723 2017-05-26 09:41
    关注

    To start, we need to ensure that the we're dealing with a slice by testing: reflect.TypeOf(<var>).Kind() == reflect.Slice

    Without that check, you risk a runtime panic. So, now that we know we're working with a slice, finding the element type is as simple as: typ := reflect.TypeOf(<var>).Elem()

    Since we're likely expecting many different element types, we can use a switch statement to differentiate:

    t := reflect.TypeOf(<var>)
    if t.Kind() != reflect.Slice {
        // handle non-slice vars
    }
    switch t.Elem().Kind() {  // type of the slice element
        case reflect.Int:
            // Handle int case
        case reflect.String:
            // Handle string case
        ...
        default:
            // custom types or structs must be explicitly typed
            // using calls to reflect.TypeOf on the defined type.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等