指向struct的nil指针不深等于nil吗? [英] Nil pointer to struct not deep equal to nil?

查看:136
本文介绍了指向struct的nil指针不深等于nil吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个结构,其中包含类型为Anil指针,则使用reflect.DeepEqual检查该属性是否为nil将导致false,这使我感到奇怪.

If I have a struct containing a nil pointer of type A, using reflect.DeepEqual to check if that property is nil will result in false, which strikes me as odd behaviour.

type Container struct {
    O *Obj
}

type Obj struct {
    Message string
}

var c Container
eq := reflect.DeepEqual(c.O, nil)
fmt.Printf("O value: %v, is nil: %t", c.O, eq)
// Prints: "O value: <nil>, is nil: false"

具体地说,我将JSON对象编组到一个结构中,当相应的JSON结构不包含该属性时,我想在其中测试特定属性为nil.如果reflect.DeepEqual没办法,我应该怎么做?

Specifically, I am marshaling a JSON object into a struct, where I would like to test that a specific property is nil when the corresponding JSON structure does not contain it. If reflect.DeepEqual is not the way to go, how should I do this?

推荐答案

您传递给 包装在interface{}值中(如果还没有的话):

Everything you pass to reflect.DeepEqual() is wrapped in an interface{} value (if it's not already that):

func DeepEqual(x, y interface{}) bool

interface{}值将被比较,其中第一个参数值不是nil ,只有包装在其中的值.

interface{} values will be compared, where the first parameter value is not nil, only the value wrapped in it.

接口值表示为(type; value)对.您传递给reflect.DeepEqual()的第一个值是一对(type; value),即(*Obj, nil),第二个值是nil.他们是不平等的.第二个值缺少类型信息.

An interface value is represented as a (type; value) pair. The first value you pass to reflect.DeepEqual() is a pair of (type; value) being (*Obj, nil), and the 2nd value is nil. They are not equal. The second value lacks type information.

如果将其与键入"的nil进行比较,则将为true:

If you compare it to a "typed" nil, it will be true:

reflect.DeepEqual(c.O, (*Obj)(nil)) // This is true

请参见以下示例:

fmt.Println("c.O:", c.O)
fmt.Println("c.O == nil:", c.O == nil)
fmt.Println("c.O deep equal to nil:", reflect.DeepEqual(c.O, nil))
fmt.Println("c.O deep equal to (*Obj)(nil):", reflect.DeepEqual(c.O, (*Obj)(nil)))

输出(在游乐场上尝试):

c.O: <nil>
c.O == nil: true
c.O deep equal to nil: false
c.O deep equal to (*Obj)(nil): true

请参阅此问题以获取更深入的了解:

See this question for a deeper insight:

隐藏nil值,了解为什么golang在这里失败

如果要检查包装在非nil接口中的值是否为nil,则可以使用反射:

If you want to check if the value wrapped inside a non-nil interface is nil, you can use reflection: reflect.Value.IsNil().

有关更多详细信息,请参见:为什么接口类型不不会提供"IsNil"方法?

For more details see: Why interface type doesn't provide an "IsNil" method?

这篇关于指向struct的nil指针不深等于nil吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆