doupingpeng7567 2017-02-14 04:23
浏览 339
已采纳

v == nil如何返回false和reflect.ValueOf(v).IsNil()同时返回true?

Here's some code:

var v interface{}
v = (*string)(nil)

// Reflect says it is nil
val := reflect.ValueOf(v)
if val.IsNil() {
    fmt.Println("val is nil")
} else {
    fmt.Println("val is not nil")
}

// This says it is not nil
if v == nil {
    fmt.Println("v is nil")
} else {
    fmt.Println("v is not nil")
}

https://play.golang.org/p/apyPa4CNZ6

The output is:

val is nil

v is not nil

How is this possible? Is v nil or not?

Also, if you change the first two lines with

v := (*string)(nil)

then the output clearly states that the variable is nil.

Right now in my project I have a function that accepts a argument of type interface{} and I can't reliably check if it is nil with a simple v == nil. I would like to avoid using the reflect package.

  • 写回答

1条回答 默认 最新

  • duanjie9630 2017-02-14 04:40
    关注

    From golang.org:

    Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).

    An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil.

    You can try fmt.Printf("(%v, %T) ", v, v). It prints (<nil>, *string).

    When you change first two lines to v := (*string)(nil), v is just a pointer, not an interface.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题