Home > Mobile >  how to use reflect know the slice data type?
how to use reflect know the slice data type?

Time:08-17

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

CodePudding user response:

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

CodePudding user response:

if you want get the type to slice you can refer to this page :

https://www.geeksforgeeks.org/reflect-sliceof-function-in-golang-with-examples/#:~:text=SliceOf() Function in Golang is used to get the,reflect package in the program.&text=Parameters: This function takes only,of Type type(t).

  • Related