我正在使用反射包来获取任意数组的类型,但是获取
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
发布于 2013-10-16 03:48:52
更改:
GetTypeArray(arr []interface{})至:
GetTypeArray(arr interface{})顺便说一句,[]int不是一个数组,而是一个整数片段。
发布于 2014-07-11 06:59:39
索引切片的事实是不安全的-如果它是空的,您将得到索引超出范围的运行时恐慌。无论如何,由于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()传递非分片值并导致死机。
https://stackoverflow.com/questions/19389629
复制相似问题