dtv8189 2013-12-01 07:21
浏览 82
已采纳

是否可以为命名的类型/结构定义相等性?

After reading a related question about using slices in maps, I became curious about equality in Go.

I know it's possible to override the equals method of a Java Object. Is there a similar way to define how Go checks user defined types/structs for equality? If so, there would be a workaround for the issue referenced above. I thought using interface{} values might offer a solution but I received the error message panic: runtime error: hash of unhashable type []int.

  • 写回答

2条回答 默认 最新

  • dongwen3093 2016-11-10 18:51
    关注

    Go supports equality checking structs.

    type Person struct {
        Name string
    }
    
    a := Person{"Bill DeRose"}
    b := Person{"Bill DeRose"}
    
    a == b // true
    

    It won't work with pointer fields (in the way you want) because the pointer addresses are different.

    type Person struct {
        Friend *Person
    }
    
    a := Person{Friend: &Person{}}
    b := Person{Friend: &Person{}}
    
    a == b // false
    

    You can't modify the equality operator and there is no built-in way to add support for custom types to use == syntax. Instead you should compare the pointer values using reflect.DeepEqual.

    import "reflect"
    
    a := Person{Friend: &Person{}}
    b := Person{Friend: &Person{}}
    
    reflect.DeepEqual(a, b) // true
    

    Keep in mind there are caveats.

    In general DeepEqual is a recursive relaxation of Go's == operator. However, this idea is impossible to implement without some inconsistency. Specifically, it is possible for a value to be unequal to itself, either because it is of func type (uncomparable in general) or because it is a floating-point NaN value (not equal to itself in floating-point comparison), or because it is an array, struct, or interface containing such a value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取