我正在使用 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 http://play.golang.org/p/sNw8aL0a5f
事实上,你对切片建立索引是不安全的——如果它是空的,你会得到一个索引超出范围的运行时恐慌。无论如何,这是没有必要的,因为反映包的Elem() method http://golang.org/pkg/reflect/#Type:
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()
运行时的非切片值并出现恐慌。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)