![](/img/trans.png)
[英]Is there a difference between `assert_eq!(a, b)` and `assert_eq!(a, b, )`?
[英]What is the difference between "eq()" and "=="?
这就是 std 所说的:
pub trait PartialEq<Rhs: ?Sized = Self> {
/// This method tests for `self` and `other` values to be equal, and is used
/// by `==`.
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
fn eq(&self, other: &Rhs) -> bool;
/// This method tests for `!=`.
#[inline]
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
fn ne(&self, other: &Rhs) -> bool {
!self.eq(other)
}
}
和链接: https://doc.rust-lang.org/src/core/cmp.rs.html#207
这是我的代码:
fn main() {
let a = 1;
let b = &a;
println!("{}", a==b);
}
编译器告诉我:
error[E0277]: can't compare `{integer}` with `&{integer}`
--> src\main.rs:4:21
|
4 | println!("{}", a==b);
| ^^ no implementation for `{integer} == &{integer}`
|
= help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`
但是当我使用eq()
时,它编译:
fn main() {
let a = 1;
let b = &a;
println!("{}", a.eq(b));
}
它实际上很简单,但它需要一些知识。 表达式a == b
是PartialEq::eq(&a, &b)
的语法糖(否则,如果我们正在处理非Copy
类型,我们将通过尝试测试它们是否相等来移动a
和b
) .
在我们的例子中,function PartialEq::eq
需要两个 arguments,它们都是&i32
类型。 我们看到a: i32
和b: &i32
。 因此, &b
将具有类型&&i32
,而不是&i32
。
通过尝试比较具有不同类型的两个事物,我们会得到一个类型错误是有道理的。 a
具有i32
类型, b
具有&i32
类型,因此无论编译器如何秘密实现a == b
,我们都可能在尝试执行时遇到类型错误。
另一方面,在a: i32
的情况下,表达式a.eq(b)
是PartialEq::eq(&a, b)
的语法糖。 这里有一个微妙的区别 - 没有&b
。 在这种情况下, &a
和b
都有类型&i32
,所以这完全没问题。
a.eq(b)
和a == b
之间的区别在于,点运算符对按引用调用方法的接收器类型执行 autoref/autoderef。
因此,当您编写a.eq(b)
时,编译器会查看PartialEq::eq(&self, other: &Rhs)
签名,查看&self
引用并将其添加到a
。
当您编写a == b
时,它对PartialEq::eq(a, b)
where a: i32
b: &i32
在您的情况下,因此错误no implementation for `{integer} == &{integer}`
。
但是为什么它在运营商中没有做同样的事情呢? 请参阅跟踪问题:在运算符中允许 autoderef 和 autoref(实验)#44762
相关信息: Rust 的确切自动取消引用规则是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.