dongmei3498 2014-08-14 05:17
浏览 72
已采纳

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

  • 写回答

2条回答 默认 最新

  • dtu15253 2014-08-14 21:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog