[英]Golang: get the type of slice
我使用反射包来获取任意数组的类型,但得到
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])
}
您正在为切片编制索引这一事实是不安全的 - 如果它是空的,您将获得索引超出范围的运行时混乱。 无论如何,由于反射包的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()
传递给非切片值并引起恐慌。
更改:
GetTypeArray(arr []interface{})
至:
GetTypeArray(arr interface{})
顺便说一下, []int
不是一个数组,而是一个整数切片 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.