1

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)
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
Mojito
  • 27
  • 2
  • `fmt.Println(fieldType.Elem())` – icza Jun 30 '21 at 10:24
  • @icza: would you mind re-posting your comment as an answer so it could be upvoted and accepted? This could lead to a better experience for folks googling and finding this question in the future – Eli Bendersky Jun 30 '21 at 13:42

1 Answers1

2

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
icza
  • 389,944
  • 63
  • 907
  • 827