目前我正在使用这个辅助函数来检查 nil 和 nil 接口
func isNil(a interface{}) bool {
defer func() { recover() }()
return a == nil || reflect.ValueOf(a).IsNil()
}
Since reflect.ValueOf(a).IsNil()
if the value’s Kind is anything other than Chan
, Func
, Map
, Ptr
, Interface
或 Slice
,我投入了延迟的 recover()
来捕捉那些。
有没有更好的方法来实现这个检查?它认为应该有更直接的方法来做到这一点。
原文由 user187676 发布,翻译遵循 CC BY-SA 4.0 许可协议
例如,请参阅 Kyle 在 golang-nuts 邮件列表的 线程 中的回答。
简而言之:如果您从不在接口中存储
(*T)(nil)
,那么您可以可靠地使用与 nil 的比较,无需使用反射。另一方面,将无类型的 nil 分配给接口总是可以的。