Golang:得到切片的类型

时间:2013-10-15 19:40:35

标签: arrays go reflection slice go-reflect

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

   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

2 个答案:

答案 0 :(得分:27)

您正在为切片编制索引这一事实是不安全的 - 如果它是空的,您将获得索引超出范围的运行时混乱。无论如何,由于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

    ...
}

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

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

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

答案 1 :(得分:4)

变化:

GetTypeArray(arr []interface{})

为:

GetTypeArray(arr interface{})

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

相关问题