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)