Rust 中两个引用变量如何相等?

Avi*_*ava 8 rust

我的代码在其中一个函数中存在错误:

fn is_five(x: &i32) -> bool {
    x == 5
}

fn main() {
    assert!(is_five(&5));
    assert!(!is_five(&6));
    println!("Success!");
}
Run Code Online (Sandbox Code Playgroud)

运行时,报错为:

error[E0277]: can't compare `&i32` with `{integer}`
 --> main.rs:2:7
  |
2 |     x == 5
  |       ^^ no implementation for `&i32 == {integer}`
  |
  = help: the trait `std::cmp::PartialEq<{integer}>` is not implemented for `&i32`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
Run Code Online (Sandbox Code Playgroud)

我通过比较两个值而不是一个地址和一个值的逻辑来修复它。

fn is_five(x: &i32) -> bool {
    *x == 5
}
Run Code Online (Sandbox Code Playgroud)

然而,我也尝试(随机)使用借用方法,令我惊讶的是,它有效。

fn is_five(x: &i32) -> bool {
    x == &5
}
Run Code Online (Sandbox Code Playgroud)

我不明白两个地址怎么可以相同?是否该==运算符有某种特征可以获取两端存储的值?

Bro*_*ind 5

要想做到==,就必须落实PartialEq。如果您查看此处的文档,您可以看到如果类型A实现了PartialEq<B>&'_ A实现PartialEq<&'_ B>。换句话说,如果可以比较值,则可以使用引用来比较它们。

同样的推理适用于其他比较特征:EqPartialOrd、 和Ord,以及可变引用。

  • “如果你可以比较值,你就可以比较它们的指针”有点误导,因为当你写“x == &amp;5”时,比较的不是指针,而是它们指向的值。 (3认同)
  • 请注意,您不是在比较指针,而是在比较引用。[比较指针将比较指针本身而不是指向的值](https://play.rust-lang.org/?version=nightly&amp;mode=release&amp;edition=2018&amp;gist=dd44ace432ba539fb288f44aa87eb266) (2认同)