Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang reflect value kind of slice

Tags:

go

fmt.Println(v.Kind())
fmt.Println(reflect.TypeOf(v))

How can I find out the type of the reflect value of a slice?

The above results in

v.Kind = slice
typeof = reflect.Value

When i try to Set it will crash if i create the wrong slice

t := reflect.TypeOf([]int{})
s := reflect.MakeSlice(t, 0, 0)
v.Set(s)

For example []int{} instead of []string{} so I need to know the exact slice type of the reflect value before I create one.

like image 911
Gert Cuykens Avatar asked May 26 '17 09:05

Gert Cuykens


1 Answers

To start, we need to ensure that the we're dealing with a slice by testing: reflect.TypeOf(<var>).Kind() == reflect.Slice

Without that check, you risk a runtime panic. So, now that we know we're working with a slice, finding the element type is as simple as: typ := reflect.TypeOf(<var>).Elem()

Since we're likely expecting many different element types, we can use a switch statement to differentiate:

t := reflect.TypeOf(<var>)
if t.Kind() != reflect.Slice {
    // handle non-slice vars
}
switch t.Elem().Kind() {  // type of the slice element
    case reflect.Int:
        // Handle int case
    case reflect.String:
        // Handle string case
    ...
    default:
        // custom types or structs must be explicitly typed
        // using calls to reflect.TypeOf on the defined type.
}
like image 185
SnoProblem Avatar answered Nov 08 '22 11:11

SnoProblem