繁体   English   中英

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

[英]how to use reflect know the slice data type?

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

在我知道切片数据类型之前,匆忙设置值会恐慌,有人知道如何获取切片类型信息吗?

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
    }
}

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

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
    }
}

操场

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

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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM