首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用反射知道切片数据类型?

如何使用反射知道切片数据类型?
EN

Stack Overflow用户
提问于 2022-08-17 07:57:17
回答 3查看 164关注 0票数 -2

我想填充切片数据,但是使用reflect.kind()只让我知道字段(0)是片,但我不知道它是哪种类型的片,它是int[]还是string[]还是其他类型的片

我知道什么切片数据类型,仓促设定值会恐慌,有些知道如何获取切片类型的信息吗?

代码语言:javascript
复制
func WhatSlice(isAny any) {
    vof := reflect.ValueOf(isAny)
    if vof.Kind() != reflect.Struct {
        return
    }
    switch vof.Field(0).Kind() {
    case reflect.Slice:
        for i := 0; i < vof.Field(0).Len(); i++ {
            // how to know this field is []int or []string?
            // vof.Field(0).Index(i).Set()
        }
    default:
        return
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-08-17 10:09:53

使用Type,您可以直接获得切片类型,但是应该使用字符串类型来区分它。

代码语言:javascript
复制
func WhatSlice(isAny any) {
    vof := reflect.ValueOf(isAny)

    if vof.Kind() != reflect.Struct {
        return
    }

    switch vof.Field(0).Kind() {
    case reflect.Slice:
        switch vof.Field(0).Type().String() {
        case "[]int":
            fmt.Println("int here")
        case "[]string":
            fmt.Println("string here")
        }
    default:
        return
    }
}
票数 1
EN

Stack Overflow用户

发布于 2022-08-17 08:14:20

您可以在使用vof.Field(0).Index(0).Kind()调用循环之前检查它。

代码语言:javascript
复制
func WhatSlice(isAny any) {
    vof := reflect.ValueOf(isAny)
    if vof.Kind() != reflect.Struct {
        return
    }
    switch vof.Field(0).Kind() {
    case reflect.Slice:
        if vof.Field(0).Len() == 0 {
            fmt.Println("empty slice")
            return
        }
        switch vof.Field(0).Index(0).Kind() {
        case reflect.Int:
            fmt.Println("int here")
            // for i := 0; i < vof.Field(0).Len(); i++ {
            // how to know this field is []int or []string?
            // vof.Field(0).Index(i).Set()
            // }
        case reflect.String:
            fmt.Println("string here")
        }
    default:
        return
    }
}

游乐场

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73384785

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档