Golang: get the type of slice

天涯浪子 提交于 2019-12-05 00:51:10

Change:

GetTypeArray(arr []interface{})

to:

GetTypeArray(arr interface{})

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:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!