问题描述
据我所知,引用之间的相等比较是比较引用对象的值,而不是引用中包含的地址。即它们隐式地取消引用引用。
既然如此,为什么还要写:
if ref_to_foo == &another_foo {
而不是
if ref_to_foo == another_foo {
什么时候
if ref_to_foo == ref_to_another_foo {
双方是否已经隐式解除引用?
显而易见的答案是“因为编译器创造了我”,但我试图理解为什么语言设计者认为这是一个坏主意。
解决方法
在编写 a==b
时,编译器理解 PartialEq::eq(&a,&b)
。
因此,在编写 &a==&b
时,编译器理解 PartialEq::eq(&&a,&&b)
。
This documentation 指向此源代码
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)
}
}
表明 PartialEq::eq(&&a,&&b)
的实现只是取消引用参数,以便将调用转发到 PartialEq::eq(&a,&b)
(因此,最后与 a==b
相同)。
似乎不存在任何 PartialEq
的默认实现只取消引用两个参数之一,因此 a==&b
和 &a==b
应该被拒绝。