Golan: get the cut type

I use a reflection package to get the type of an arbitrary array, but I get

prog.go:17: cannot use sample_array1 (type []int) as type []interface {} in function argument [process exited with non-zero status] 

How to get a type from an array? I know how to get it from the cost.

  func GetTypeArray(arr []interface{}) reflect.Type { return reflect.TypeOf(arr[0]) } 

http://play.golang.org/p/sNw8aL0a5f

+6
source share
2 answers

Edit:

 GetTypeArray(arr []interface{}) 

in

 GetTypeArray(arr interface{}) 

By the way, []int is not an array, but a fragment of integers.

+4
source

The fact that you are indexing a slice is unsafe - if it is empty, you will get panic in standby mode out of range. Regardless, this is not necessarily due to the package reflects the Elem() method :

 type Type interface { ... // Elem returns a type element type. // It panics if the type Kind is not Array, Chan, Map, Ptr, or Slice. Elem() Type ... } 

So here is what you want to use:

 func GetTypeArray(arr interface{}) reflect.Type { return reflect.TypeOf(arr).Elem() } 

Please note that in accordance with the change of @tomwilde, the arr argument can be of any type at all, so there is nothing stopping you from passing a GetTypeArray() unsharp value at runtime and getting a panic.

+19
source

Source: https://habr.com/ru/post/956012/


All Articles