Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reflection

go

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?

like image 746
F21 Avatar asked Jan 20 '17 04:01

F21


1 Answers

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())
}
like image 109
F21 Avatar answered Sep 25 '22 20:09

F21