使用反射包比较指针值

huangapple go评论70阅读模式
英文:

Comparing pointer values using reflect package

问题

我有一个包含许多字段的结构体,我想要检查这些字段中是否有任何一个为空,而不必手动输入每个字段的名称。这些字段的类型始终是指针,所以我可以轻松地进行检查而不必担心零值。

我尝试使用反射包来实现这一点,但似乎没有正常工作,我无法弄清楚原因。

这里有一个复制了我的问题的playground链接:
http://play.golang.org/p/LOb6a8eklE

你可以看到,如果我手动检查,一切都正常。当要求打印时,它也打印出null,但是当进行比较时,结果却为false。

对此有什么想法吗?

我主要的猜测是Interface()的返回类型显然是interface{},并且通过将"null"存储在其中,它不再是"null"。有没有什么解决方法?

谢谢!

英文:

I have a struct with a lot of fields and I have to check if any of those fields is null without having to type every field name by hand. The field's type is always a pointer so I can check without having to worry about zero-values.

I'm trying to to this using the reflection package, but it doesn't seem to be working properly and I can't figure out why.

Here is a playground replicating my problem:
http://play.golang.org/p/LOb6a8eklE

As you can see, if I check by hand everything works fine. When asked to print it prints null as well, but when comparing it evaluates to false.

Any thoughts on what is going on?

My main guess is because the return type of Interface() is, obviously, interface{}, and by storing "null" inside it, it doesn't make it "null" anymore. Any way around that?

Thanks!

答案1

得分: 0

使用IsNil()来判断指针是否为nil。

<kbd>playground</kbd>

表达式v.Interface() == nil始终为false,因为Interface()返回一个带有关联类型的值。

有关此主题的更多信息,请参阅nil error FAQ

英文:

Use IsNil() to determine if a pointer is nil.

<kbd>playground</kbd>

The expression v.Interface() == nil is always false because Interface() returns a value with an associated type.

See the nil error FAQ for more information on this topic.

huangapple
  • 本文由 发表于 2014年10月14日 02:29:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/26346530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定