rust - 实现 `Eq` 的目的是什么?

标签 rust

无论 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);
}

最佳答案

来自the documentation from Eq :

Trait for equality comparisons which are equivalence relations.

This means, that in addition to a == b and a != b being strict inverses, the equality must be (for all a, b and c):

  • reflexive: a == a;
  • symmetric: a == b implies b == a; and
  • transitive: a == b and b == c implies a == c.

This property cannot be checked by the compiler, and therefore Eq implies PartialEq, 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/

相关文章:

exception - 如何在不将整个事情变成嵌套 for 循环的情况下在迭代链中引发错误?

dll - 有没有办法将版本信息存储在 Rust 编译的可执行文件或库中?

rust - 闭包何时实现Fn,FnMut和FnOnce?

rust - 我应该如何重组图形代码以避免出现 "Cannot borrow variable as mutable more than once at a time"错误?

casting - 如何将 Vec<Box<dyn Trait>> 移动到 Vec<Rc<RefCell<dyn Trait>>>

rust - 从同一个 HashMap 中借用两个可变值

rust - 如何为参数化特征实现特征

asynchronous - 如何在启动异步操作和在循环中等待其结果之间有一个宽限期?

rust - 无法从 Rocket 路由返回字符串

rust - 如何使用 Iron 创建自定义内容类型?