how to use reflect know the slice data type?

1.4k views Asked by At

i want to fill the slice data , but using reflect.kind() only let me know field(0) is slice , but i don't know it is which type of slice , it culd be int[] or string[] or other type slice

befor i know what slice data type , hastily set value will panic , do some know how to get slice type info?

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

There are 3 answers

1
NoahFan On BEST ANSWER

Use the Type you can directly get the slice type but should use the string type to distinguish it.

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
    }
}
2
Rahmat Fathoni On

You can check it before call for loop with 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
    }
}

playground