5

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?

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
Mihai H
  • 3,291
  • 4
  • 25
  • 34
  • The slice is of type `[]inteface{}` so the underlying type is `interface{}`. Meaning it can have anything in it. If you want the underlying type of **each element** you need to check it for each element. – Not_a_Golfer Jun 23 '14 at 13:21
  • Try v := &[]Foo{...} and see the difference. – Mihai H Jun 23 '14 at 13:24
  • I don't know of a better way to get a `reflect` object representing the `interface{}` type than using an instance of it like you're doing. Might be able to avoid `reflect`: w/an `var ifc interface{}` that might represent an `*[]interface{}` or a `*[]Foo`, you can always do `_, ok := ifc.(*[]interface{})` and check `ok` to see if you got the type right, or do a type switch (check the spec on those). Also, note [a slice already contains a pointer to the data so you rarely need slice pointers](http://stackoverflow.com/questions/23542989/best-practice-returning-structs-in-go/23551970#23551970). – twotwotwo Jun 23 '14 at 18:00
  • But how would you retrieve the array type using reflection. Let us assume the we have v := make([]Foo, 0). How to get the Foo type and not []Foo? – Mihai H Jun 24 '14 at 02:55
  • Silly me, found it: valType.Elem().Elem() – Mihai H Jun 24 '14 at 03:01
  • 3
    @MihaiH Good that you apparently found an answer. It seems you have forgot to provide an answer and accept it! – user918176 Nov 18 '15 at 20:26

1 Answers1

3

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()
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250