In Go, which value’s kind is reflect.Interface?

go, reflection

Solution

You can not get directly the type of an `interface{}` value, but you can go through a pointer indirection (asking for the type of `*interface{}` and then asking the pointed type):

reflect.TypeOf((*interface{})(nil)).Elem()

Going through a slice type is the same mental exercise (asking for the type of `[]interface{}` and then asking the slice element type):

reflect.TypeOf([]interface{}(nil)).Elem()

Go 1.22 added `reflect.TypeFor` which makes it much simpler:

reflect.TypeFor[interface{}]()
reflect.TypeFor[any]()          // any is a type alias for interface{}

Run this on play.golang.org:

t := reflect.TypeOf((*interface{})(nil)).Elem()
fmt.Printf("Type: %s\n", t)
fmt.Printf("Kind: %v\n", t.Kind())
fmt.Printf("IsInterface: %v\n", t.Kind() == reflect.Interface)

Output:

Type: interface {}
Kind: interface
IsInterface: true

Problem

``` j:=1 ``` `Kind` of `j` is `reflect.Int`, as expected. ``` var j interface{} = 1 ``` `Kind` of `j` is also `reflect.Int`. Which value’s kind is `reflect.Interface`?

Original source