15

I am using reflect package to get the type of arbitrary array, but getting

   prog.go:17: cannot use sample_array1 (type []int) as type []interface {} in function argument [process exited with non-zero status]

How do I get the type from array? I know how to get it from value.

  func GetTypeArray(arr []interface{}) reflect.Type {
      return reflect.TypeOf(arr[0])
  }

http://play.golang.org/p/sNw8aL0a5f

2 Answers2

39

The fact that you're indexing the slice is unsafe - if it's empty, you'll get an index-out-of-range runtime panic. Regardless, it's unnecessary because of the reflect package's Elem() method:

type Type interface {

    ...

    // Elem returns a type's element type.
    // It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
    Elem() Type

    ...
}

So, here's what you want to use:

func GetTypeArray(arr interface{}) reflect.Type {
      return reflect.TypeOf(arr).Elem()
}

Note that, as per @tomwilde's change, the argument arr can be of absolutely any type, so there's nothing stopping you from passing GetTypeArray() a non-slice value at runtime and getting a panic.

Mike
  • 1,569
  • 2
  • 14
  • 20
  • Please also note @thwd's semantics note: `[]int` is a _slice_ of integers, not an array. Don't get confused by the use of "Array" and "arr" here. `GetTypeArray` will work for either - array or slice - and therefore a name like `GetElemType` would be better. – Nathaniel Jones Nov 23 '21 at 18:48
4

Change:

GetTypeArray(arr []interface{})

to:

GetTypeArray(arr interface{})

By the way, []int is not an array but a slice of integers.

thwd
  • 23,956
  • 8
  • 74
  • 108
  • 4
    This doesn't solve the issue of the potential index-out-of-bounds panic. See my answer. – Mike Jul 10 '14 at 23:00
  • @Mike Even though you are correct, that is not the question (which includes a very specific error to solve) and hence it's out of scope here. – thwd Jul 11 '14 at 06:50
  • 3
    The title of the question is "Golang , Go : get the type of array", and that's what I was looking for when I found it. I'm not suggesting that it's your bug or that you missed it. However, it's important that it be addressed because I almost used this code without noticing the bug or the fact that the solution was suboptimal. I'm not trying to challenge you, I just think it's important. – Mike Jul 11 '14 at 17:16