在 Go 中通过反射检测空值的快速方法 [英] Quick way to detect empty values via reflection in Go

查看:17
本文介绍了在 Go 中通过反射检测空值的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 int/string/bool/etc.. 值存储在 interface{}并想确定它是否未初始化,这意味着它的值是

I have a int/string/bool/etc.. value stored in an interface{} and want to determine if it's uninitialized, meaning that it has a value of either

  • 0
  • ""
  • nil

我该如何检查?

推荐答案

Go 1.13(2019 年第三季度)应该简化检测过程:

Go 1.13 (Q3 2019) should simplify that detection process:

新的Value.IsZero() 方法报告 Value 是否为其类型的零值.

The new Value.IsZero() method reports whether a Value is the zero value for its type.

它在src中实现/reflect/value.go,来自 commit c40bffdCL 171337,解决了issue 7501

参见 playground 示例(一旦支持 Go 1.13)

See playground example (as soon as Go 1.13 is supported)

这篇关于在 Go 中通过反射检测空值的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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