13

我正在使用反射包来获取任意数组的类型,但是得到

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

如何从数组中获取类型?我知道如何从价值中得到它。

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

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

4

2 回答 2

38

您正在索引切片的事实是不安全的 - 如果它是空的,您将得到一个 index-out-of-range 运行时恐慌。无论如何,由于反射包的Elem()方法,它是不必要的:

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

    ...
}

所以,这就是你想要使用的:

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

请注意,根据@tomwilde 的更改,参数arr绝对可以是任何类型,因此没有什么可以阻止您GetTypeArray()在运行时传递非切片值并引起恐慌。

于 2014-07-10T22:59:39.223 回答
4

改变:

GetTypeArray(arr []interface{})

至:

GetTypeArray(arr interface{})

顺便说一句,[]int不是数组而是整数切片

于 2013-10-15T19:48:51.640 回答