dpj96988 2017-01-20 04:45
浏览 259
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • dtz63853 2017-01-20 05:16
    关注

    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())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog