Reputation: 27
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)
}
Upvotes: 1
Views: 463
Reputation: 417512
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
Upvotes: 2