美文网首页
go struct/interface equality 用户自

go struct/interface equality 用户自

作者: cdz620 | 来源:发表于2020-03-03 00:24 被阅读0次

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

参考文档:

相关文章

网友评论

      本文标题:go struct/interface equality 用户自

      本文链接:https://www.haomeiwen.com/subject/allikhtx.html