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)
双方已经隐式解除引用?
显而易见的答案是“因为编译器创造了我”,但我试图理解为什么语言设计者认为这是一个坏主意。
编写时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应予以拒绝。
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |