Search code examples
goreflection

why reflect.TypeOf(new(Encoder)).Elem() != reflect.TypeOf(interfaceVariable)?


Here's the short test:

type Encoder interface {
    Encode()
}
func main() {
    encoderInterface1 := reflect.TypeOf(new(Encoder)).Elem()
    var en Encoder
    encoderInterface2 := reflect.TypeOf(en)
    fmt.Println(encoderInterface1 == encoderInterface2)
}

Outputs false.

Why is it false? I was expecting it to be true.


Solution

  • From the reflect.TypeOf docs:

    TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

    Therefore:

    var en Encoder // nil interface value
    
    encoderInterface2 := reflect.TypeOf(en) // <- nil
    

    As for:

    encoderInterface1 := reflect.TypeOf(new(Encoder)).Elem()
    

    breaking this into two parts:

    pi := reflect.TypeOf(new(Encoder)) // <- this is a pointer to an interface (so not nil)
    encoderInterface1 := pi.Elem()
    

    So:

    encoderInterface1 != encoderInterface2
    

    because:

    encoderInterface1 != nil