为什么 Rust 期望双重借用 (`&&'a mut T`)

Why does Rust expect double borrow (`&&'a mut T`)

我的代码看起来像 this:

pub enum Cache<'a, T> {
    Pending(&'a dyn FnOnce() -> T),
    Cached(T),
}

impl<'a, T> Cache<'a, T> {
    pub fn get(&self) -> &mut T {
        // This caches and borrows the T
    }
}

impl<'a, T> PartialEq for Cache<'a, T>
    where &'a mut T: PartialEq {

    fn eq(&self, other: &Self) -> bool {
        self.get().eq(other.get())
    }
}

但是实施 Eq 失败了:

error[E0308]: mismatched types
--> src/lib.rs:20:23
|
20 |         self.get().eq(other.get())
|                       ^^^^^^^^^^^ expected mutable reference, found type parameter
|
= note: expected type `&&'a mut T`
               found type `&mut T`

我想我在概念上误解了一些东西。

通过查看 PartialEq 特征中 eq() 方法的定义,您可以理解为什么 Rust 期望 &&mut T

fn eq(&self, other: &Rhs) -> bool;

该方法的参数类型为&Self&Rhs;由于 Rhs 默认为 Self 并且您没有在特征范围中指定任何其他内容,因此两个参数都应为 &Self.

类型

现在在这种情况下 Self 是什么?你的特质界限是这样的:

&'a mut T: PartialEq

所以编译器唯一可以使用的PartialEq实现是&'a mut T类型的实现,所以这就是Self&Self 反过来必须是 &&'a mut T,这正是编译器所期望的。

您可能想要 T 的特征绑定:

impl<'a, T> PartialEq for Cache<'a, T>
where
    T: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.get() == other.get()
    }
}

另请注意,您可以简单地使用 == 而不是显式调用 eq()。它使正确的类型更容易一些,因为编译器将隐式引用参数 – a == b 扩展为 PartialEq::eq(&a, &b).