自定义的struct,可以比较;有些限制如下(比较的不一致性)
- float 值 NaN不等于NaN
- func Type funcA 不等于 func Type funcA
- 包含Array,struct, interface
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.
基于以上说明的不确定性,能不能自定义相等(==)运算符?
答案:不行,go 有严格的==
运算符设计,无法重载或自定义相等运算符,见:https://golang.org/ref/spec#Comparison_operators
如何实现自定义相等比较,曲线救国,如下方法:
- 使用
reflect.DeepEqual
方法,有些限制见文档:https://golang.org/pkg/reflect/#DeepEqual - 用自定义实现DeepEqual方法,
go type identity 类型比较
go spec定义的类型比较:https://golang.org/ref/spec#Type_identity
参考文档:
网友评论