为什么 Rust 不让我比较 Foo 和 &Foo?

fad*_*bee 1 equality reference rust

据我了解,引用之间的相等比较比较的是引用对象的值,而不是引用中包含的地址。即它们隐式地取消引用引用。

既然如此,为什么还要写:

if ref_to_foo == &another_foo {
Run Code Online (Sandbox Code Playgroud)

而不是

if ref_to_foo == another_foo {
Run Code Online (Sandbox Code Playgroud)

什么时候

if ref_to_foo == ref_to_another_foo {
Run Code Online (Sandbox Code Playgroud)

双方已经隐式解除引用?

显而易见的答案是“因为编译器创造了我”,但我试图理解为什么语言设计者认为这是一个坏主意。

pro*_*-fh 5

编写时a==b,编译器理解PartialEq::eq(&a, &b)

因此,在编写 时&a==&b,编译器会理解PartialEq::eq(&&a, &&b)

此文档导致此源代码

    impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
    where
        A: PartialEq<B>,
    {
        #[inline]
        fn eq(&self, other: &&B) -> bool {
            PartialEq::eq(*self, *other)
        }
        #[inline]
        fn ne(&self, other: &&B) -> bool {
            PartialEq::ne(*self, *other)
        }
    }
Run Code Online (Sandbox Code Playgroud)

表明实现PartialEq::eq(&&a, &&b)简单地取消引用参数以将调用转发到PartialEq::eq(&a, &b)(因此,与最后相同a==b)。

似乎没有存在的任何默认实现PartialEq其提领操作只有两个参数之一,因此a==&b&a==b应予以拒绝。

  • 我认为问题是,为什么该语言不专门处理这种情况(比较引用与非引用),以提高使用的工效性,就像它处理其他各种事情一样,例如函数调用中的自动取消引用。原因包括与其他语言功能的交互不良,或者由于编译器的限制而难以或不可能实现等。 (2认同)