简体   繁体   中英

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. How do I compare the value of that pointer against the zero-value of its type?

reflect.Zero() returns a reflect.Value . reflect.New() returns a pointer to a zero value.

I updated the function to check the case where x is a pointer to something:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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