[英]Golang: get the type of slice
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 http://play.golang.org/p/sNw8aL0a5f
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 : 无论如何,由于反射包的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
...
}
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. 请注意,根据@ tomwilde的更改,参数arr
可以是绝对任何类型,因此没有什么能阻止您在运行时将GetTypeArray()
传递给非切片值并引起恐慌。
Change: 更改:
GetTypeArray(arr []interface{})
to: 至:
GetTypeArray(arr interface{})
By the way, []int
is not an array but a slice of integers. 顺便说一下, []int
不是一个数组,而是一个整数切片 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.