如何获取切片的元素类型?

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

How to get the element type of slice?

问题

如果有这样的结构体:

type A struct {
  Arr []int
}

我如何获取切片Arr中的元素类型?

例如,传入一个空的A实例,我如何获取int类型?

func PrintElementType(obj interface{}) {
	objType := reflect.TypeOf(obj)
	for i := 0; i < objType.NumField(); i++ {
		fieldType := objType.Field(i).Type
		// 这里我得到了'slice'
		fmt.Println(fieldType.Kind())
		// 这里我得到了'[]int',我认为'int'类型被存储在某个地方...
		fmt.Println(fieldType)
		// 那么,有没有办法获取'int'类型呢?
		fmt.Println("内部元素类型?")
	}
}

func main() {
	a := A{}
	PrintElementType(a)
}
英文:

If there is a struct like:

type A struct {
  Arr []int
}

How can I get the element type in the slice arr?

for example, an empty A instance is passed in, how can I get the int type?

func PrintElementType(obj interface{}) {
	objType := reflect.TypeOf(obj)
	for i := 0; i &lt; objType.NumField(); i++ {
		fieldType := objType.Field(i).Type
		// here I got &#39;slice&#39;
		fmt.Println(fieldType.Kind())
		// here I got &#39;[]int&#39;, I think &#39;int&#39; type is stored somewhere...
		fmt.Println(fieldType)
		// so, is there any way to get &#39;int&#39; type?
		fmt.Println(&quot;inner element type?&quot;)
	}
}

func main() {
	a := A{}
	PrintElementType(a)
}

答案1

得分: 2

如果你有一个切片类型的reflect.Type类型描述符,可以使用它的Type.Elem()方法来获取切片元素类型的描述符:

fmt.Println(fieldType.Elem())

如果类型的Kind是ArrayChanMapPtrSlice,也可以使用Type.Elem()来获取元素类型,但如果不是这些类型,它会引发panic。因此,在调用之前应该检查类型的kind:

if fieldType.Kind() == reflect.Slice {
    fmt.Println("Slice's element type:", fieldType.Elem())
}

这将输出以下结果(在Go Playground上尝试):

slice
[]int
Slice's element type: int
英文:

If you have the reflect.Type type descriptor of a slice type, use its Type.Elem() method to get the type descriptor of the slice's element type:

fmt.Println(fieldType.Elem())

Type.Elem() may also be used to get the element type if the type's Kind is Array, Chan, Map, Ptr, or Slice, but it panics otherwise. So you should check the kind before calling it:

if fieldType.Kind() == reflect.Slice {
    fmt.Println(&quot;Slice&#39;s element type:&quot;, fieldType.Elem())
}

This will output (try it on the Go Playground):

slice
[]int
Slice&#39;s element type: int

huangapple
  • 本文由 发表于 2021年6月30日 18:22:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/68192963.html
匿名

发表评论

匿名网友

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

确定