无论 Eq
是否实现,以下 rust 程序都会输出相同的结果。那为什么还要费力去实现Eq
呢?实现 Eq
会在哪些方面产生影响?
fn main() {
struct S(i32);
impl PartialEq for S {
fn eq(&self, _: &Self) -> bool {
return false;
}
}
impl Eq for S {} // ?
let s1 = S(3);
let s2 = S(4);
println!("{}", s1 == s1);
println!("{}", s1 == s2);
}
最佳答案
Trait for equality comparisons which are equivalence relations.
This means, that in addition to
a == b
anda != b
being strict inverses, the equality must be (for alla
,b
andc
):
- reflexive:
a == a
;- symmetric:
a == b
impliesb == a
; and- transitive:
a == b
andb == c
impliesa == c
.This property cannot be checked by the compiler, and therefore
Eq
impliesPartialEq
, and has no extra methods.
如果您在类型上实现 Eq
,您就断言自反、对称和传递规则适用于您的 PartialEq
实现。这无法进行类型检查,因此 Rust 信任程序员只有在知道它实际上满足该条件时才会实现 Eq。这使得某些原本无法工作的算法能够工作,例如HashMap
。
换句话说,Eq
是告诉编译器“我的类型遵循上述规则”的方式。
注意:无需输入 impl Eq for S {}
,只需在 S< 的声明上输入
.#[derive(Eq)]
即可
关于rust - 实现 `Eq` 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74189363/