簡體   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