Go接口是(type,nil)或(type,value)

Hi I want ask a question about interface is nil

//i think err should be a interface (*MyError, nil)
var err error = (*MyError)(nil)
fmt.Println(reflect.TypeOf(err)) 
fmt.Println(reflect.ValueOf(err))` 

the result told me interface value is not nil result :

*main.MyError
<*main.MyError Value>

it's equivalent to interface (*main.MyError, <*main.MyError Value>) why the interface value is not nil?

thanks

These two things are completely different:

  • The nil interface value. It does not hold an underlying type or value.

  • A non-nil interface value, which holds an underlying type and value, and that underlying value is nil in that underlying type (if it's one of the types that have a value called nil -- pointer, slice, map, channel, or function). Note that different types' nils are different and unrelated (pointer-nil and map-nil are unrelated); and some types don't have a value called nil.

You have a nil pointer (*MyError type), and you assign that to an interface variable (first of interface type error, then converted to interface type interface{} which is the parameter type of reflect.TypeOf() and reflect.ValueOf()). Therefore, those functions receive a non-nil interface value containing an underlying type *MyError and underlying value nil.

reflect.TypeOf(err) gets the underlying type, which is *MyError. And reflect.ValueOf(err) constructs a reflect.Value object representing the underlying type and value. This is what you see.

The stringification of a reflect.Value produces the string <T value>, where T is the type, but it doesn't try to stringily the value (nil pointer in this case). If you wanted to print the underlying value, perhaps you should have just done fmt.Println(err) instead.

http://golang.org/pkg/reflect/#ValueOf

ValueOf returns a new Value initialized to the concrete value stored in the interface i. ValueOf(nil) returns the zero Value.