[英]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.