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])
}
Change:
to:
By the way,
[]int
is not an array but a slice of integers.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:So, here's what you want to use:
Note that, as per @tomwilde's change, the argument
arr
can be of absolutely any type, so there's nothing stopping you from passingGetTypeArray()
a non-slice value at runtime and getting a panic.