什么时候只需要 PartialEq 而不需要 Eq 是合适的?
When is it appropriate to require only PartialEq and not Eq?
我正在阅读 the Rust book 并试图了解 PartialEq
和 Eq
特征的用例。
我意识到 PartialEq
用于不一定自反的关系(即可以有这样的 x
x != x
)并且 Eq
是标记特征这表明该关系也是自反的(现在它是一个适当的等价关系)。
书中给出了一个示例,其中 PartialEq
是不够的,需要 Eq
:HashMap<K, V>
查找。事实上,如果我们使用仅实现 PartialEq
的数据类型作为键(例如浮点数),当我们尝试使用 NaN
作为键时我们会遇到麻烦,因为我们不会找不到它。
现在,我正试图了解查找的什么特性使其需要 Eq
。如果我找到一个不需要 Eq
的代码示例,我可能会更好地理解它。
书上说 assert_eq!
只需要 PartialEq
这样我们就可以比较事物是否相等。但是如果我们在测试中写 assert_eq!(f64::NAN, some_code_producing_nan());
,测试总是会失败。我们有与在 HashMap
中使用 PartialEq
密钥相同的基本问题,但出于某种原因,它在这里被认为是合适的。
什么是只需要 PartialEq
并且添加 Eq
的合理函数的示例 desirable/does 没有意义?
如果没有这样的用例,那我们为什么要关心将其拆分为两个特征 PartialEq
/ Eq
? Haskell,例如,刚好有Eq
.
决定何时使用 PartialEq
与 Eq
应该基于使用是否需要 x == x
。
问题不在于是否可以将 x
与 x
进行比较,而是如果发生这种比较,使用是否取决于 x==x
始终保持不变?如果答案是肯定的,请使用 Eq
。否则更喜欢较弱的约束 PartialEq
。
assert_eq!
不依赖于 x==x
始终持有,因此无需对调用者施加该约束。正如 OP 在评论中简洁地提到的 2 个示例:
if we do assert_eq!(NAN, produces_nan())
- it's our problem that it gives false
, but if we do a lookup of a NAN
key in a HashMap
, it would be a problem of the HashMap
, because it would violate its lookup contract (that it should be able to find all the keys put in the map)
我正在阅读 the Rust book 并试图了解 PartialEq
和 Eq
特征的用例。
我意识到 PartialEq
用于不一定自反的关系(即可以有这样的 x
x != x
)并且 Eq
是标记特征这表明该关系也是自反的(现在它是一个适当的等价关系)。
书中给出了一个示例,其中 PartialEq
是不够的,需要 Eq
:HashMap<K, V>
查找。事实上,如果我们使用仅实现 PartialEq
的数据类型作为键(例如浮点数),当我们尝试使用 NaN
作为键时我们会遇到麻烦,因为我们不会找不到它。
现在,我正试图了解查找的什么特性使其需要 Eq
。如果我找到一个不需要 Eq
的代码示例,我可能会更好地理解它。
书上说 assert_eq!
只需要 PartialEq
这样我们就可以比较事物是否相等。但是如果我们在测试中写 assert_eq!(f64::NAN, some_code_producing_nan());
,测试总是会失败。我们有与在 HashMap
中使用 PartialEq
密钥相同的基本问题,但出于某种原因,它在这里被认为是合适的。
什么是只需要 PartialEq
并且添加 Eq
的合理函数的示例 desirable/does 没有意义?
如果没有这样的用例,那我们为什么要关心将其拆分为两个特征 PartialEq
/ Eq
? Haskell,例如,刚好有Eq
.
决定何时使用 PartialEq
与 Eq
应该基于使用是否需要 x == x
。
问题不在于是否可以将 x
与 x
进行比较,而是如果发生这种比较,使用是否取决于 x==x
始终保持不变?如果答案是肯定的,请使用 Eq
。否则更喜欢较弱的约束 PartialEq
。
assert_eq!
不依赖于 x==x
始终持有,因此无需对调用者施加该约束。正如 OP 在评论中简洁地提到的 2 个示例:
if we do
assert_eq!(NAN, produces_nan())
- it's our problem that it givesfalse
, but if we do a lookup of aNAN
key in aHashMap
, it would be a problem of theHashMap
, because it would violate its lookup contract (that it should be able to find all the keys put in the map)