在Go中检查零和无界面 [英] Check for nil and nil interface in Go
问题描述
目前我使用这个帮助函数来检查nil和nil接口。
$ b
func isNil(a interface {}) bool {
defer func(){recover()}()
return a == nil ||由于 reflect.ValueOf(a).IsNil()
如果值的种类不是 Chan
, Func
, Map , Ptr
,界面
或 Slice
,我抛出延迟的 recover()
来捕获这些。
有没有更好的方法来完成这项检查?它认为应该有一个更直接的方式来做到这一点。
解决方案请参阅凯尔的线程在golang-nuts邮件列表中。
简而言之:如果您从未在界面中存储(* T)(nil)
,那么您可以可靠地使用与零比较,无需使用反射。另一方面,将无类型nil分配给接口总是可以的。
Currently I'm using this helper function to check for nil and nil interfaces
func isNil(a interface{}) bool {
defer func() { recover() }()
return a == nil || reflect.ValueOf(a).IsNil()
}
Since reflect.ValueOf(a).IsNil()
panics if the value's Kind is anything other than Chan
, Func
, Map
, Ptr
, Interface
or Slice
, I threw in the deferred recover()
to catch those.
Is there a better way to achieve this check? It think there should be a more straight forward way to do this.
解决方案 See for example Kyle's answer in this thread at the golang-nuts mailing list.
In short: If you never store (*T)(nil)
in an interface, then you can reliably use comparison against nil, no need to use reflection. On the other hand, assigning untyped nil to an interface is always OK.
这篇关于在Go中检查零和无界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!