go struct/interface equality 用户自定义类型比较

自定义的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

如何实现自定义相等比较,曲线救国,如下方法:

go type identity 类型比较

go spec定义的类型比较:https://golang.org/ref/spec#Type_identity

参考文档:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。