Search code examples
goslicereflect

how to use reflect know the slice data type?


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

Solution

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