go - 如何使用 reflect.DeepEqual() 将指针的值与其类型的零值进行比较?

标签 go reflection

我需要一个通用函数来检查某物是否等于它的零值。

从这里question ,我能够找到一个适用于值类型的函数。我修改它以支持指针:

func isZeroOfUnderlyingType(x interface{}) bool {

    rawType := reflect.TypeOf(x)

    //source is a pointer, convert to its value
    if rawType.Kind() == reflect.Ptr {
        rawType = rawType.Elem()
    }

    return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}

不幸的是,当我做这样的事情时,这对我不起作用:

type myStruct struct{}

isZeroOfUnderlyingType(myStruct{}) //Returns true (works)

isZeroOfUnderlyingType(&myStruct{}) //Returns false (doesn't) work

这是因为 &myStruct{} 是一个指针,无法在函数内部取消引用 interface{}。如何将该指针的值与其类型的零值进行比较?

最佳答案

reflect.Zero() 返回一个 reflect.Valuereflect.New() 返回一个指向零值的指针。

我更新了函数以检查 x 是指向某物的指针的情况:

func isZeroOfUnderlyingType(x interface{}) bool {

    rawType := reflect.TypeOf(x)

    if rawType.Kind() == reflect.Ptr {
        rawType = rawType.Elem()
        return reflect.DeepEqual(x, reflect.New(rawType).Interface())
    }

    return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}

关于go - 如何使用 reflect.DeepEqual() 将指针的值与其类型的零值进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41756279/

相关文章:

google-app-engine - 在 App Engine 中使用 rpc/jsonrpc

go - 字符串的结构名称

Go lang, channel 处理顺序

c# - 在 C# 中使用反射向对象添加属性

c# - 获取所有引用程序集的路径

从 Google Drive 下载公共(public)文件 - Golang

go - Go 中的命令行标志可以设置为强制吗?

c# - 获取未知类型列表的计数

Java 反射 - 访问 protected 字段

swift - Swift 中结构类型的反射