rust - 为什么 1 == &2 不能编译?
问题描述
我尝试编译以下代码以了解应用于引用的比较运算符的行为:
fn main() {
&1 == &2; // OK
&&1 == &&2; // OK
&1 == &mut 2; // OK
&mut(&1) == &(&mut 2); // OK
1 == &2; // Compilation Error
&1 == &&2; // Compilation Error
}
根据这个结果,对于类型T
实现PartialEq
,似乎
- s 的引用
T
,s 的引用T
,... 的引用是可比较的。 - 共享和可变引用可以混合使用。
- 两边的引用数量
==
必须相同。
这些规则从何而来?规则 1 和 2 可以从比较运算符和 deref 强制的语义中得出。考虑&1 == &mut 2
:
- 该表达式被
PartialEq::eq(&&1, &(&mut 2))
编译器解释为。 - 第一个参数
&&1
变成&1
了 deref coercion 因为&T
implementsDeref<Target = T>
。 - 第二个参数
&(&mut 2)
变成&2
了 deref coercion 因为&mut T
implementsDeref<Target = T>
。 PartialEq::eq
现在,两个参数的类型都与implemented by的签名相匹配i32
。如此PartialEq::<i32>::eq(&1, &2)
评价。
但是,我不明白规则 3 的来源。我认为PartialEq::eq(&1, &&2)
是强制的,PartialEq::eq(&1, &2)
因为 deref 强制独立应用于两个参数。
规则 3 的基本原理是什么?请在编译器中显示 Rust 的文档语义或适当的代码?
解决方案
使用运算符时似乎没有发生 deref 强制(我不确定为什么会这样),但是由于PartialEq
.
从PartialEq
以下实现的 Rust 文档可以看出:
impl<'a, 'b, A, B> PartialEq<&'b B> for &'a A
where
A: PartialEq<B> + ?Sized,
B: ?Sized,
这表明存在类型借用和类型B
借用A
的实现,如果存在PartialEq
for type A
and的实现B
。
给定这个定义,&i32 == &i32
可以使用因为i32
implementsPartialEq
并且给定上面的 impl,这个指令PartialEq
是为借用i32
s 实现的。这会导致递归情况&&i32 == &&i32
有效,因为PartialEq
是为&i32
所以实现的,因为上面的 implPartialEq
也是为 实现的&&i32
。
由于此实现的定义,双方的借用次数必须相同。
推荐阅读
- java - 针对在 Hyper-V 虚拟机中运行的 SQL Server 诊断慢速 JDBC 选择语句
- firebase - 如何使用 Firebase 创建电子商务网站
- javascript - 如何将 React 代码放入单独的文件中?
- c++ - Visual Studio 内存窗口字节顺序
- amazon-web-services - 在 AWS 中进行写入、版本和差异的最便宜的方法是什么?
- python - 如何在列表变量中重复一个值以在 matplotlib 中为条形图着色?
- android - 在android中更改View Pager2所选图像的图像视图背景
- google-apps-script - SpreadsheetApp.getActiveSpreadsheet() 返回:指定对象必须是工作表的一部分
- swiftui - 带有变量的 navigationBarTitle 给出了各种随机错误
- php - 实现用户日志的最佳方式