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

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

问题描述

我有一个 int / 字符串 / bool / etc .. value存储在 interface {} 中,并且想要确定它是否未初始化,这意味着它的值为




  • 0


  • false

  • nil


  • 我该如何检查?

    解决方案

    {
    return x == reflect.Zero(reflect.TypeOf(x))。Interface()
    }

    在讨论接口和 nil 时,人们总是会对两个截然不同而又毫无关联的东西感到困惑:


    1. 一个 nil 接口值,它是一个没有基础值的接口值 。这是接口类型的零值。

    2. 非 - nil 接口值(即它有一个基础值),但其基础值是其基础类型的零值。例如基础值是 nil 地图, nil 指针或0号码等。

    我的理解是你在问第二件事。






    更新:由于上述代码使用 == ,因此它不适用于不可比较的类型。我相信使用 reflect.DeepEqual()可以让它适用于所有类型:

      func IsZeroOfUnderlyingType(x interface {})bool {
    return reflect.DeepEqual(x,reflect.Zero(reflect.TypeOf(x)).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
    • ""
    • false
    • or nil

    How do I check this?

    解决方案

    From what I understand, you want something like:

    func IsZeroOfUnderlyingType(x interface{}) bool {
        return x == reflect.Zero(reflect.TypeOf(x)).Interface()
    }
    

    When talking about interfaces and nil, people always get confused with two very different and unrelated things:

    1. A nil interface value, which is an interface value that doesn't have an underlying value. This is the zero value of an interface type.
    2. A non-nil interface value (i.e. it has an underlying value), but its underlying value is the zero value of its underlying type. e.g. the underlying value is a nil map, nil pointer, or 0 number, etc.

    It is my understanding that you are asking about the second thing.


    Update: Due to the above code using ==, it won't work for types that are not comparable. I believe that using reflect.DeepEqual() instead will make it work for all types:

    func IsZeroOfUnderlyingType(x interface{}) bool {
        return reflect.DeepEqual(x, reflect.Zero(reflect.TypeOf(x)).Interface())
    }
    

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

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