Golang:获取切片的类型

huangapple go评论138阅读模式
英文:

Golang: get the type of slice

问题

我正在使用reflect包来获取任意数组的类型,但是得到了以下错误信息:

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

我该如何从数组中获取类型?我知道如何从值中获取类型。

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

你可以在这个链接中查看示例代码:http://play.golang.org/p/sNw8aL0a5f

英文:

I am using reflect package to get the type of arbitrary array, but getting

  1. 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.

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

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

答案1

得分: 39

你正在索引切片的事实是不安全的——如果它是空的,你将得到一个索引越界的运行时恐慌。不管怎样,这是不必要的,因为反射包的Elem()方法可以解决这个问题:

  1. type Type interface {
  2. ...
  3. // Elem返回类型的元素类型。
  4. // 如果类型的Kind不是Array、Chan、Map、Ptr或Slice,则会引发恐慌。
  5. Elem() Type
  6. ...
  7. }
  8. 所以这是你想要使用的代码
  9. ```go
  10. func GetTypeArray(arr interface{}) reflect.Type {
  11. return reflect.TypeOf(arr).Elem()
  12. }

请注意,根据@tomwilde的更改,参数arr可以是任何类型,所以你可以在运行时传递一个非切片值给GetTypeArray(),并得到一个恐慌。

英文:

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:

  1. type Type interface {
  2. ...
  3. // Elem returns a type's element type.
  4. // It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
  5. Elem() Type
  6. ...
  7. }

So, here's what you want to use:

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

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.

答案2

得分: 4

将:

  1. GetTypeArray(arr []interface{})

改为:

  1. GetTypeArray(arr interface{})

顺便说一下,[]int 不是一个数组,而是一个整数的 切片

英文:

Change:

  1. GetTypeArray(arr []interface{})

to:

  1. GetTypeArray(arr interface{})

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

huangapple
  • 本文由 发表于 2013年10月16日 03:40:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/19389629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定