有没有可能为命名类型/结构定义相等性? [英] Is it possible to define equality for named types/structs?
问题描述
阅读相关问题,关于在地图中使用切片后,我成了对Go的平等很好奇。
After reading a related question about using slices in maps, I became curious about equality in Go.
我知道可以覆盖Java <$ c $的等于
方法C>对象。是否有类似的方式来定义Go如何检查用户定义的类型/结构是否相等?如果是这样,那么对于上面引用的问题将有一个解决方法。我想过使用 界面{}
值可能会提供一个解决方案,但我收到了错误消息 panic:运行时错误:不可用类型的哈希[] int
。
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
.
推荐答案
Go支持相等检查结构。
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
您无法修改相等运算符,也没有内置方法来添加对自定义类型的支持以使用 = =
语法。相反,您应该使用 reflect.DeepEqual
来比较指针值。 。
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.
一般来说,DeepEqual是Go的==运算符的递归放松。然而,这个想法是不可能实现的,没有一些不一致。具体而言,一个值可能与自身不相等,或者是因为它是func类型(通常无法比较),或者因为它是浮点型NaN值(在浮点比较中不等于自身),或者因为它是浮点型它是包含这样一个值的数组,结构或接口。
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.
这篇关于有没有可能为命名类型/结构定义相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!