英文:
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 < objType.NumField(); i++ {
fieldType := objType.Field(i).Type
// here I got 'slice'
fmt.Println(fieldType.Kind())
// here I got '[]int', I think 'int' type is stored somewhere...
fmt.Println(fieldType)
// so, is there any way to get 'int' type?
fmt.Println("inner element type?")
}
}
func main() {
a := A{}
PrintElementType(a)
}
答案1
得分: 2
如果你有一个切片类型的reflect.Type类型描述符,可以使用它的Type.Elem()方法来获取切片元素类型的描述符:
fmt.Println(fieldType.Elem())
如果类型的Kind是Array、Chan、Map、Ptr或Slice,也可以使用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("Slice's element type:", fieldType.Elem())
}
This will output (try it on the Go Playground):
slice
[]int
Slice's element type: int
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论