简体   繁体   English

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

[英]How do I use reflect.DeepEqual() to compare a pointer's value against the zero value of its type?

I need a generic function to check whether something is equal to its zero-value or not. 我需要一个通用函数来检查某项是否等于其零值。

From this question , I was able to find a function that worked with value types. 通过这个问题 ,我能够找到一个适用于值类型的函数。 I modified it to support pointers: 我修改了它以支持指针:

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())
}

Unfotunately, this didn't work for me when doing something like this: 不幸的是,当执行以下操作时,这对我不起作用:

type myStruct struct{}

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

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

This is because &myStruct{} is a pointer and there is no way to dereference an interface{} inside the function. 这是因为&myStruct{}是指针,并且无法在函数内部取消引用interface{} How do I compare the value of that pointer against the zero-value of its type? 如何将指针的值与其类型的零值进行比较?

reflect.Zero() returns a reflect.Value . reflect.Zero()返回一个reflect.Value reflect.New() returns a pointer to a zero value. reflect.New()返回一个指向零值的指针。

I updated the function to check the case where x is a pointer to something: 我更新了该函数以检查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())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM