Skip to content

Go Reflect: Correctly Get an Empty Interface Type

This blog records the tricky part of using reflect to get an empty interface type correctly. The background is that a component requires the configuration type during function call as it might use the type to construct a type and set up the value based on some external data set. If we cannot find a respective in some scenarios, empty interface type should be passed.

However, at the beginning due to the wrong usage of reflect, a nil type instead of interface{} type is passed by reflect.TypeOf(i).

var i interface{}
// this is correct
typ := reflect.TypeOf(&i).Elem()

// this is wrong usage, the typ is nil
typ := reflect.TypeOf(i)

What's the Issue?

The code below prints nil and interface{} for the code below.

    var i interface{}
    fmt.Print(reflect.TypeOf(i))
    fmt.Print(reflect.TypeOf(&i).Elem())

The explanation is that the declaration var i interface defines an interface with a nil underlying type.

i: interface{nil}

Hence, the reflect.TypeOf(i) indeed returns the type of the underlying type, which is nil. To get the empty interface, we need to pass the pointer &i into reflect.TypeOf, so the interface received by TypeOf is:

interface { *interface{nil} }

The TypeOf(&i) gets the *interface{nil}, and Elem de-references the pointer and returns the interface{nil}.