jeudi 19 janvier 2017

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?





Aucun commentaire:

Enregistrer un commentaire