Reflect slice underlying type

Mih*_*i H 5 reflection go slice

I have the following code:

v: = &[]interface{}{client, &client.Id}
valType := reflect.TypeOf(v)
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
        elm := val.Elem()
        if elm.Kind() == reflect.Slice {
            fmt.Println("Type ->>", elm, " - ", valType.Elem())
        }
    }
Run Code Online (Sandbox Code Playgroud)

The output is the following one: Type ->> <[]interface {} Value> - []interface {} How can I get the underlying type of it? I would like to check if array type is of interface{} kind.

EDIT One way to achieve it, an ugly way IMHO is this one:

var t []interface{}
fmt.Println("Type ->>", elm, " - ", valType.Elem(), " --- ", reflect.TypeOf(t) == valType.Elem())
Run Code Online (Sandbox Code Playgroud)

Can it be done in a different way?

Von*_*onC 3

让我们假设我们有v := make([]Foo, 0)
如何获取Foo类型而不是类型[]Foo

正如您所发现的,valType.Elem().Elem()在您使用切片指针的情况下,可以工作。

但对于常规切片,如“ golang 反射切片的值类型”中所示,这就足够了:

typ := reflect.TypeOf(<var>).Elem()
Run Code Online (Sandbox Code Playgroud)