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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?