简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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