[golang] Why is the value of the interface variable not nil?

Posted Jun 6, 20202 min read

Test code

package main

import(
    "fmt"

)

func main() {
    doIt := func(args int) interface{} {
        var result *struct{} = nil
        if args> 0 {
            result = &struct{}{}
        }
        return result
    }

    if res := doIt(-1); res != nil {
        fmt.Println("res != nil")
    } else {
        fmt.Println("res == nil")
    }
}

The above code outputs res != nil

The return type of doIt is interface{} empty interface, in the code var result *struct{} = nil is nil, but the returned result is interface{}, empty interface

For the empty interface, the empty interface type can save any value, or you can take the original value from the empty interface

The interface type itself cannot be valued. Before we give it the actual value, its value must be nil, which is also its zero value. Conversely, once it is assigned a value of an implementation type, its value is no longer nil.

The returned empty interface contains the type information(type) and data pointer(data) that point to the object result. That is, the value of the interface variable is not equivalent to this copy that can be called a dynamic value(result). It will contain two pointers, one pointer to the dynamic value(result) and one pointer to the type information**

iface & eface