go struct/interface equality 用户自

2020-03-03  本文已影响0人  cdz620

自定义的struct,可以比较;有些限制如下(比较的不一致性)

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

参考文档:

上一篇 下一篇

猜你喜欢

热点阅读