Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflect slice underlying type

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

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())

Can it be done in a different way?

like image 751
Mihai H Avatar asked Nov 01 '22 21:11

Mihai H


1 Answers

Let us assume the we have v := make([]Foo, 0).
How to get the Foo type and not []Foo?

As you have found out, valType.Elem().Elem() can work, in your case where you are using a slice pointer.

But for a regular slice, as in "golang reflect value kind of slice", this would be enough:

typ := reflect.TypeOf(<var>).Elem()
like image 123
VonC Avatar answered Nov 15 '22 08:11

VonC